From a5445100050e49e83f73424198d73cd72d672a4d Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 4 Mar 2018 14:53:33 +0200 Subject: Sync Integ to Master Change-Id: I71e3acc26fa612127756ac04073a522b9cc6cd74 Issue-ID: SDC-977 Signed-off-by: Gitelman, Tal (tg851x) --- catalog-be/DME2preferredRouter.txt | 0 catalog-be/pom.xml | 317 +- .../files/default/normatives.tar.gz | Bin 102084 -> 105414 bytes .../templates/default/BE-configuration.yaml.erb | 53 + .../BE-distribution-engine-configuration.yaml.erb | 38 +- .../sdc/be/auditing/api/AuditEventFactory.java | 16 + .../sdc/be/auditing/api/IAuditingManager.java | 29 - .../impl/AuditAuthRequestEventFactory.java | 28 + .../be/auditing/impl/AuditBaseEventFactory.java | 114 + .../auditing/impl/AuditConsumerEventFactory.java | 42 + .../auditing/impl/AuditEcompOpEnvEventFactory.java | 29 + .../impl/AuditResourceEventFactoryMananger.java | 76 + .../auditing/impl/AuditingLogFormatConstants.java | 569 +- .../be/auditing/impl/AuditingLogFormatUtil.java | 503 +- .../sdc/be/auditing/impl/AuditingManager.java | 228 +- .../category/AuditAddCategoryEventFactory.java | 13 + .../AuditAddGroupingCategoryEventFactory.java | 13 + .../category/AuditAddSubCategoryEventFactory.java | 13 + .../impl/category/AuditCategoryEventFactory.java | 34 + .../AuditGetCategoryHierarchyEventFactory.java | 30 + .../AuditAddKeyDistribEngineEventFactory.java | 12 + ...AuditAddRemoveKeyDistribEngineEventFactory.java | 23 + .../AuditCreateTopicDistribEngineEventFactory.java | 21 + .../AuditDistribDeployEventFactory.java | 35 + .../AuditDistribDownloadEventFactory.java | 33 + .../AuditDistribEngineEventFactory.java | 23 + .../AuditDistribNotificationEventFactory.java | 39 + .../AuditDistribStatusEventFactory.java | 33 + .../AuditGetUebClusterEventFactory.java | 30 + .../AuditRegUnregDistribEngineEventFactory.java | 21 + .../AuditRegisterDistribEngineEventFactory.java | 12 + .../AuditRemoveKeyDistribEngineEventFactory.java | 12 + .../AuditUnregisterDistribEngineEventFactory.java | 12 + ...uditActivateServiceExternalApiEventFactory.java | 26 + .../AuditAssetExternalApiEventFactory.java | 25 + ...ditAssetGetMetadataExternalApiEventFactory.java | 16 + .../AuditAssetListExternalApiEventFactory.java | 24 + ...uditChangeLifecycleExternalApiEventFactory.java | 27 + ...AuditCreateResourceExternalApiEventFactory.java | 28 + .../AuditCrudExternalApiArtifactEventFactory.java | 27 + ...tDeleteArtByApiCrudExternalApiEventFactory.java | 16 + ...ditDownloadArtifactExternalApiEventFactory.java | 23 + .../externalapi/AuditExternalApiEventFactory.java | 25 + .../AuditGetAssetListExternalApiEventFactory.java | 16 + ...etFilteredAssetListExternalApiEventFactory.java | 16 + .../AuditGetToscaModelExternalApiEventFactory.java | 16 + ...tUpdateArtByApiCrudExternalApiEventFactory.java | 16 + ...tUploadArtByApiCrudExternalApiEventFactory.java | 16 + .../AuditArtifactResourceAdminEventFactory.java | 33 + ...uditCertificationResourceAdminEventFactory.java | 30 + ...AuditCreateUpdateResourceAdminEventFactory.java | 30 + ...tateChangeRequestResourceAdminEventFactory.java | 30 + ...itDistStateChangeResourceAdminEventFactory.java | 31 + .../AuditImportResourceAdminEventFactory.java | 34 + .../AuditResourceAdminEventFactory.java | 30 + .../usersadmin/AuditGetUsersListEventFactory.java | 31 + .../usersadmin/AuditUserAccessEventFactory.java | 34 + .../usersadmin/AuditUserAdminEventFactory.java | 33 + .../clean/AsdcComponentsCleanerTask.java | 175 - .../clean/ComponentsCleanBusinessLogic.java | 89 - .../csar/CsarArtifactsAndGroupsBusinessLogic.java | 1681 +++ .../distribution/engine/AaiRequestHandler.java | 84 + .../distribution/engine/ArtifactInfoImpl.java | 336 +- .../distribution/engine/CambriaErrorResponse.java | 88 +- .../distribution/engine/CambriaHandler.java | 1081 +- .../engine/DME2EndpointIteratorCreator.java | 19 + .../distribution/engine/DeConfigurationStatus.java | 40 - .../distribution/engine/DistributionEngine.java | 633 +- .../engine/DistributionEngineClusterHealth.java | 557 +- .../engine/DistributionEngineInitTask.java | 512 +- .../engine/DistributionEnginePollingTask.java | 343 +- .../engine/DistributionNotificationSender.java | 161 +- .../engine/DistributionStatusNotification.java | 122 +- .../engine/DistributionStatusNotificationEnum.java | 2 +- .../distribution/engine/DmaapClientFactory.java | 91 + .../distribution/engine/DmaapConsumer.java | 76 + .../distribution/engine/DmaapHealth.java | 220 + .../engine/DmaapNotificationDataImpl.java | 65 + .../engine/EnvironmentMessageBusData.java | 75 + .../distribution/engine/EnvironmentsEngine.java | 526 + .../distribution/engine/ExecutorFactory.java | 43 + .../distribution/engine/IArtifactInfo.java | 70 +- .../distribution/engine/IDistributionEngine.java | 37 +- .../engine/IDmaapAuditNotificationData.java | 6 + .../engine/IDmaapNotificationData.java | 76 + .../distribution/engine/INotificationData.java | 158 +- .../distribution/engine/INotificationHandler.java | 11 + .../distribution/engine/IResourceArtifactInfo.java | 22 +- .../engine/JsonContainerResourceInstance.java | 224 +- .../distribution/engine/NotificationDataImpl.java | 212 +- .../engine/NotificationExecutorService.java | 79 +- .../engine/PublishNotificationRunnable.java | 156 - .../engine/ResourceArtifactInfoImpl.java | 64 +- .../engine/ServiceArtifactInfoImpl.java | 8 +- .../ServiceDistributionArtifactsBuilder.java | 503 +- .../distribution/engine/SubscriberTypeEnum.java | 2 +- .../distribution/engine/UebHealthCheckCall.java | 68 +- .../engine/VfModuleArtifactPayload.java | 183 +- .../config/DistributionEngineSpringConfig.java | 11 + .../report/DistributionCompleteReporter.java | 9 + .../report/MsoDistributionCompleteReporter.java | 19 + .../engine/rest/DistributionStatusRequest.java | 23 + .../distribution/engine/rest/MSORestClient.java | 69 + .../health/HealthCheckBusinessLogic.java | 475 + .../impl/ActivationRequestInformation.java | 42 + .../impl/AdditionalInformationBusinessLogic.java | 1007 +- .../be/components/impl/ArtifactResolverImpl.java | 8 +- .../be/components/impl/ArtifactsBusinessLogic.java | 10323 +++++++------- .../be/components/impl/AttributeBusinessLogic.java | 515 +- .../sdc/be/components/impl/BaseBusinessLogic.java | 1420 +- .../impl/CapabilityTypeImportManager.java | 161 +- .../be/components/impl/CassandraHealthCheck.java | 336 +- .../components/impl/CategoriesImportManager.java | 413 +- .../be/components/impl/CommonImportManager.java | 541 +- .../be/components/impl/ComponentBusinessLogic.java | 2154 ++- .../impl/ComponentInstanceBusinessLogic.java | 4879 ++++--- .../components/impl/CompositionBusinessLogic.java | 489 +- .../be/components/impl/ConsumerBusinessLogic.java | 528 +- .../be/components/impl/CsarValidationUtils.java | 587 +- .../be/components/impl/DataTypeImportManager.java | 402 +- .../impl/DistributionMonitoringBusinessLogic.java | 333 +- .../be/components/impl/ElementBusinessLogic.java | 2627 ++-- .../components/impl/ExternalRefsBusinessLogic.java | 127 + .../sdc/be/components/impl/GroupBusinessLogic.java | 3733 +++-- .../be/components/impl/GroupTypeBusinessLogic.java | 46 + .../be/components/impl/GroupTypeImportManager.java | 249 +- .../components/impl/HealthCheckBusinessLogic.java | 526 - .../be/components/impl/HealthCheckInformer.java | 8 + .../impl/IDeploymentArtifactTypeConfigGetter.java | 2 +- .../sdc/be/components/impl/ImportUtils.java | 1333 +- .../InformationDeployedArtifactsBusinessLogic.java | 92 - .../be/components/impl/InputsBusinessLogic.java | 2008 +-- .../impl/InterfaceLifecycleTypeImportManager.java | 165 +- .../components/impl/MonitoringBusinessLogic.java | 57 +- .../be/components/impl/PolicyBusinessLogic.java | 451 + .../components/impl/PolicyTypeBusinessLogic.java | 56 + .../components/impl/PolicyTypeImportManager.java | 185 +- .../be/components/impl/ProductBusinessLogic.java | 1673 ++- .../ProductComponentInstanceBusinessLogic.java | 43 - .../be/components/impl/PropertyBusinessLogic.java | 991 +- .../components/impl/RequirementsBusinessLogic.java | 10 +- .../be/components/impl/ResourceBusinessLogic.java | 13913 +++++++++---------- .../be/components/impl/ResourceImportManager.java | 1807 +-- .../be/components/impl/ResponseFormatManager.java | 72 +- .../be/components/impl/ServiceBusinessLogic.java | 4230 +++--- .../ServiceComponentInstanceBusinessLogic.java | 40 - .../impl/VFComponentInstanceBusinessLogic.java | 44 - .../impl/exceptions/ComponentException.java | 44 + .../impl/generic/GenericTypeBusinessLogic.java | 12 +- .../impl/utils/PolicyTypeImportUtils.java | 70 + .../impl/version/GroupMembersUpdateOperation.java | 66 + .../impl/version/PolicyTargetsUpdateOperation.java | 67 + .../impl/version/PostChangeVersionOperation.java | 11 + .../PostChangeVersionOperationOrchestrator.java | 32 + .../lifecycle/CertificationChangeTransition.java | 290 +- .../lifecycle/CertificationRequestTransition.java | 553 +- .../be/components/lifecycle/CheckinTransition.java | 201 +- .../components/lifecycle/CheckoutTransition.java | 291 +- .../components/lifecycle/LifeCycleTransition.java | 248 +- .../lifecycle/LifecycleBusinessLogic.java | 879 +- .../lifecycle/LifecycleChangeInfoBase.java | 26 +- .../lifecycle/LifecycleChangeInfoWithAction.java | 38 +- .../lifecycle/StartCertificationTransition.java | 184 +- .../lifecycle/UndoCheckoutTransition.java | 182 +- .../merge/GlobalInputsFilteringBusinessLogic.java | 9 +- .../merge/GlobalTypesMergeBusinessLogic.java | 5 +- .../be/components/merge/RelationsComparator.java | 24 +- .../be/components/merge/TopologyComparator.java | 7 +- .../merge/capability/CapabilityResolver.java | 29 + .../merge/capability/SimpleCapabilityResolver.java | 82 + .../heat/HeatEnvArtifactsMergeBusinessLogic.java | 8 +- .../merge/input/ComponentInputsMergeBL.java | 24 +- .../input/InputsValuesMergingBusinessLogic.java | 10 +- .../ComponentCapabilitiesPropertiesMergeBL.java | 103 + .../instance/ComponentInstanceArtifactsMerge.java | 13 +- ...mponentInstanceCapabiliteisPropertiesMerge.java | 47 + .../ComponentInstanceForwardingPathMerge.java | 113 + .../instance/ComponentInstanceHeatEnvMerge.java | 11 +- .../instance/ComponentInstanceInputsMergeBL.java | 77 + .../ComponentInstanceMergeDataBusinessLogic.java | 14 +- .../instance/ComponentInstanceMergeInterface.java | 3 +- .../ComponentInstancePropertiesMergeBL.java | 76 + .../ComponentInstancePropsAndInputsMerge.java | 29 +- .../instance/ComponentInstanceRelationMerge.java | 416 + .../merge/instance/ComponentsMergeCommand.java | 22 + .../merge/instance/DataForMergeHolder.java | 38 +- .../merge/instance/RelationMergeInfo.java | 49 + .../merge/instance/VfRelationsMergeInfo.java | 30 + .../property/ComponentInstanceInputsMergeBL.java | 72 - .../ComponentInstancePropertiesMergeBL.java | 73 - .../DataDefinitionsValuesMergingBusinessLogic.java | 10 +- .../merge/property/MergePropertyData.java | 4 +- .../PropertyDataValueMergeBusinessLogic.java | 51 +- .../property/PropertyInstanceMergeDataBuilder.java | 10 +- .../merge/property/PropertyValueMerger.java | 6 +- .../merge/property/ScalarPropertyValueMerger.java | 4 +- .../merge/resource/MergeResourceBLFactory.java | 3 +- .../resource/ResourceDataMergeBusinessLogic.java | 52 +- .../components/merge/utils/MergeInstanceUtils.java | 257 + .../components/path/ForwardingPathValidator.java | 173 + .../ComponentInstanceInputPropertyDecelerator.java | 75 + .../ComponentInstancePropertyDecelerator.java | 75 + .../property/DefaultPropertyDecelerator.java | 413 + .../sdc/be/components/property/GetInputUtils.java | 13 + .../property/PolicyPropertyDecelerator.java | 130 + .../property/PropertyDecelerationOrchestrator.java | 66 + .../components/property/PropertyDecelerator.java | 30 + .../scheduledtasks/AbstractScheduleTaskRunner.java | 35 + .../scheduledtasks/AsdcComponentsCleanerTask.java | 150 + .../ComponentsCleanBusinessLogic.java | 88 + .../scheduledtasks/RecoveryThreadManager.java | 163 + .../openecomp/sdc/be/components/utils/Utils.java | 42 + .../components/validation/AccessValidations.java | 34 + .../be/components/validation/ApiResourceEnum.java | 22 + .../validation/ComponentValidations.java | 113 +- .../sdc/be/components/validation/PolicyUtils.java | 216 + .../validation/ServiceDistributionValidation.java | 118 + .../be/components/validation/UserValidations.java | 110 + .../components/validation/ValidationException.java | 21 + .../be/components/validation/ValidationUtils.java | 16 + .../sdc/be/datamodel/ForwardingPaths.java | 21 + .../org/openecomp/sdc/be/datamodel/NameIdPair.java | 89 + .../sdc/be/datamodel/NameIdPairWrapper.java | 43 + .../sdc/be/datamodel/ServiceRelations.java | 29 + .../sdc/be/datamodel/api/CategoryTypeEnum.java | 16 +- .../sdc/be/datamodel/api/HighestFilterEnum.java | 2 +- .../sdc/be/datamodel/utils/ArtifactUtils.java | 142 +- .../be/datamodel/utils/NodeTypeConvertUtils.java | 92 +- .../datamodel/utils/UiComponentDataConverter.java | 455 +- .../sdc/be/distribution/AuditHandler.java | 51 +- .../be/distribution/DistributionBusinessLogic.java | 457 +- .../api/client/CambriaOperationStatus.java | 2 +- .../api/client/RegistrationRequest.java | 46 +- .../api/client/ServerListResponse.java | 14 +- .../api/client/TopicRegistrationResponse.java | 28 +- .../api/client/TopicUnregistrationResponse.java | 46 +- .../servlet/DistributionCatalogServlet.java | 496 +- .../distribution/servlet/DistributionServlet.java | 664 +- .../org/openecomp/sdc/be/dto/ExternalRefDTO.java | 29 + .../org/openecomp/sdc/be/ecomp/EcompIntImpl.java | 683 +- .../ecomp/converters/AssetMetadataConverter.java | 687 +- .../be/ecomp/converters/EcompRoleConverter.java | 44 +- .../be/ecomp/converters/EcompUserConverter.java | 155 +- .../servlet/ArtifactExternalServlet.java | 1497 +- .../be/externalapi/servlet/AssetsDataServlet.java | 642 +- .../externalapi/servlet/CrudExternalServlet.java | 1028 +- .../externalapi/servlet/ExternalRefsServlet.java | 214 + .../servlet/ServiceActivationServlet.java | 167 + .../servlet/representation/ArtifactMetadata.java | 198 +- .../servlet/representation/AssetMetadata.java | 190 +- .../servlet/representation/IAssetMetadata.java | 20 +- .../representation/ProductAssetMetadata.java | 70 +- .../ProductCategoryGroupMetadata.java | 66 +- .../ResourceAssetDetailedMetadata.java | 72 +- .../representation/ResourceAssetMetadata.java | 70 +- .../representation/ResourceInstanceMetadata.java | 126 +- .../ServiceAssetDetailedMetadata.java | 42 +- .../representation/ServiceAssetMetadata.java | 72 +- .../representation/ServiceDistributionReqInfo.java | 23 + .../ServiceDistributionRespInfo.java | 24 + .../sdc/be/filters/BasicAuthenticationFilter.java | 364 +- .../openecomp/sdc/be/filters/BeServletFilter.java | 348 +- .../be/filters/ComponentsAvailabilityFilter.java | 164 +- .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 2847 ++-- .../sdc/be/impl/DownloadArtifactLogic.java | 227 +- .../openecomp/sdc/be/impl/ForwardingPathUtils.java | 244 + .../org/openecomp/sdc/be/impl/ServletUtils.java | 39 +- .../sdc/be/impl/WebAppContextWrapper.java | 10 +- .../openecomp/sdc/be/info/ArtifactAccessInfo.java | 241 +- .../openecomp/sdc/be/info/ArtifactAccessList.java | 20 +- .../sdc/be/info/ArtifactDefinitionInfo.java | 110 +- .../sdc/be/info/ArtifactTemplateInfo.java | 630 +- .../openecomp/sdc/be/info/ArtifactTypesInfo.java | 32 +- .../sdc/be/info/CreateAndAssotiateInfo.java | 48 +- .../openecomp/sdc/be/info/DistributionStatus.java | 68 +- .../sdc/be/info/DistributionStatusInfo.java | 126 +- .../be/info/DistributionStatusListResponse.java | 14 +- .../be/info/DistributionStatusOfServiceInfo.java | 76 +- .../DistributionStatusOfServiceListResponce.java | 14 +- .../openecomp/sdc/be/info/GroupDefinitionInfo.java | 294 +- .../openecomp/sdc/be/info/GroupTemplateInfo.java | 48 +- .../openecomp/sdc/be/info/MergedArtifactInfo.java | 275 +- .../sdc/be/info/NodeTypeInfoToUpdateArtifacts.java | 41 + .../openecomp/sdc/be/info/OperationalEnvInfo.java | 123 + .../openecomp/sdc/be/info/RelatedToProperty.java | 28 + .../org/openecomp/sdc/be/info/Relationship.java | 70 + .../openecomp/sdc/be/info/RelationshipData.java | 28 + .../openecomp/sdc/be/info/RelationshipList.java | 20 + .../org/openecomp/sdc/be/info/ServiceInfo.java | 36 +- .../openecomp/sdc/be/info/ServiceVersionInfo.java | 54 +- .../org/openecomp/sdc/be/info/ServicesWrapper.java | 14 +- .../openecomp/sdc/be/info/ServletJsonResponse.java | 28 +- .../openecomp/sdc/be/info/ToscaNodeTypeInfo.java | 64 +- .../sdc/be/info/ToscaNodeTypeInterface.java | 14 +- .../sdc/be/listen/BEAppContextListener.java | 73 +- .../org/openecomp/sdc/be/mixin/GroupTypeMixin.java | 20 + .../openecomp/sdc/be/mixin/PolicyTypeMixin.java | 20 + .../org/openecomp/sdc/be/monitoring/EsGateway.java | 115 +- .../be/servlets/AbstractValidationsServlet.java | 1692 ++- .../be/servlets/AdditionalInformationServlet.java | 912 +- .../openecomp/sdc/be/servlets/ArtifactServlet.java | 1108 +- .../sdc/be/servlets/AttributeServlet.java | 448 +- .../sdc/be/servlets/BeGenericServlet.java | 440 +- .../sdc/be/servlets/BeMonitoringServlet.java | 276 +- .../sdc/be/servlets/ComponentExceptionMapper.java | 37 + .../sdc/be/servlets/ComponentInstanceServlet.java | 2207 +-- .../sdc/be/servlets/ComponentServlet.java | 708 +- .../sdc/be/servlets/ConfigMgrServlet.java | 117 +- .../openecomp/sdc/be/servlets/ConfigServlet.java | 61 +- .../openecomp/sdc/be/servlets/ConsumerServlet.java | 325 +- .../sdc/be/servlets/CsarBuildServlet.java | 192 +- .../sdc/be/servlets/DefaultExceptionMapper.java | 21 + .../be/servlets/DistributionServiceServlet.java | 238 +- .../openecomp/sdc/be/servlets/ElementServlet.java | 1132 +- .../openecomp/sdc/be/servlets/GroupServlet.java | 412 +- .../sdc/be/servlets/GroupTypesEndpoint.java | 55 + .../openecomp/sdc/be/servlets/InputsServlet.java | 706 +- .../sdc/be/servlets/LifecycleServlet.java | 258 +- .../openecomp/sdc/be/servlets/PolicyServlet.java | 307 + .../sdc/be/servlets/PolicyTypesEndpoint.java | 64 + .../openecomp/sdc/be/servlets/ProductServlet.java | 517 +- .../openecomp/sdc/be/servlets/PropertyServlet.java | 716 +- .../sdc/be/servlets/RepresentationUtils.java | 257 +- .../sdc/be/servlets/RequirementsServlet.java | 78 +- .../servlets/ResourceArtifactDownloadServlet.java | 221 +- .../sdc/be/servlets/ResourceUploadServlet.java | 257 +- .../sdc/be/servlets/ResourcesServlet.java | 1214 +- .../be/servlets/ServiceForwardingPathServlet.java | 243 + .../openecomp/sdc/be/servlets/ServiceServlet.java | 1373 +- .../sdc/be/servlets/StorageExceptionMapper.java | 36 + .../openecomp/sdc/be/servlets/ToscaDaoServlet.java | 98 +- .../sdc/be/servlets/TypesFetchServlet.java | 150 +- .../sdc/be/servlets/TypesUploadServlet.java | 511 +- .../sdc/be/servlets/UserAdminServlet.java | 789 +- .../be/switchover/detector/SwitchoverDetector.java | 496 +- .../org/openecomp/sdc/be/tosca/ArtifactTypes.java | 18 +- .../java/org/openecomp/sdc/be/tosca/CSARTool.java | 45 - .../be/tosca/CapabiltyRequirementConvertor.java | 1081 +- .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 2894 ++-- .../openecomp/sdc/be/tosca/PropertyConvertor.java | 268 +- .../org/openecomp/sdc/be/tosca/ToscaError.java | 2 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 2307 +-- .../sdc/be/tosca/ToscaRepresentation.java | 32 +- .../org/openecomp/sdc/be/tosca/ToscaUtils.java | 158 +- .../openecomp/sdc/be/tosca/model/EntrySchema.java | 28 +- .../sdc/be/tosca/model/IToscaMetadata.java | 12 +- .../sdc/be/tosca/model/SubstitutionMapping.java | 64 +- .../sdc/be/tosca/model/ToscaCapability.java | 74 +- .../sdc/be/tosca/model/ToscaGroupTemplate.java | 62 +- .../sdc/be/tosca/model/ToscaMetadata.java | 392 +- .../sdc/be/tosca/model/ToscaNodeTemplate.java | 78 +- .../sdc/be/tosca/model/ToscaNodeType.java | 88 +- .../sdc/be/tosca/model/ToscaProperty.java | 114 +- .../sdc/be/tosca/model/ToscaRequirement.java | 24 +- .../sdc/be/tosca/model/ToscaTemplate.java | 96 +- .../be/tosca/model/ToscaTemplateCapability.java | 28 +- .../be/tosca/model/ToscaTemplateRequirement.java | 64 +- .../sdc/be/tosca/model/ToscaTopolgyTemplate.java | 62 +- .../sdc/be/tosca/model/VfModuleToscaMetadata.java | 78 +- .../be/tosca/utils/ForwardingPathToscaUtil.java | 124 + .../openecomp/sdc/be/user/IUserBusinessLogic.java | 22 +- .../main/java/org/openecomp/sdc/be/user/Role.java | 2 +- .../org/openecomp/sdc/be/user/UserAdminAction.java | 2 +- .../openecomp/sdc/be/user/UserAdminValidator.java | 64 +- .../openecomp/sdc/be/user/UserBusinessLogic.java | 1175 +- .../main/java/org/openecomp/sdc/be/view/Mixin.java | 7 + .../openecomp/sdc/be/view/MixinModelWriter.java | 60 + .../openecomp/sdc/be/view/MixinSourceTarget.java | 23 + .../org/openecomp/sdc/be/view/MixinTarget.java | 19 + .../org/openecomp/sdc/be/view/ResponseView.java | 17 + .../sdc/common/transaction/api/ICommitHandler.java | 2 +- .../sdc/common/transaction/api/IDBAction.java | 2 +- .../sdc/common/transaction/api/IDBType.java | 2 +- .../common/transaction/api/ITransactionSdnc.java | 11 +- .../common/transaction/api/RollbackHandler.java | 185 +- .../common/transaction/api/TransactionUtils.java | 112 +- .../sdc/common/transaction/impl/ESAction.java | 56 +- .../common/transaction/impl/ESRollbackHandler.java | 120 +- .../transaction/impl/TitanCommitHandler.java | 40 +- .../transaction/impl/TitanRollbackHandler.java | 46 +- .../sdc/common/transaction/mngr/CommitManager.java | 99 +- .../common/transaction/mngr/RollbackManager.java | 86 +- .../transaction/mngr/TransactionManager.java | 130 +- .../transaction/mngr/TransactionSdncImpl.java | 536 +- .../sdc/config/CatalogBESpringConfig.java | 40 + .../src/main/resources/application-context.xml | 58 +- .../main/resources/config/DME2preferredRouter.txt | 0 .../src/main/resources/config/configuration.yaml | 72 +- .../config/distribution-engine-configuration.yaml | 39 +- .../main/resources/config/error-configuration.yaml | 162 +- catalog-be/src/main/resources/config/logback.xml | 10 +- .../tosca/capability-types/capabilityTypes.yml | 12 + .../tosca/capability-types/capabilityTypes.zip | Bin 1676 -> 1735 bytes .../import/tosca/data-types/dataTypes.yml | 3 +- .../import/tosca/data-types/dataTypes.zip | Bin 6601 -> 6315 bytes .../import/tosca/group-types/groupTypes.yml | 59 +- .../import/tosca/group-types/groupTypes.zip | Bin 1088 -> 1356 bytes .../tosca/heat-types/Generic_CR/Generic_CR.json | 21 + .../tosca/heat-types/Generic_CR/Generic_CR.yml | 15 + .../tosca/heat-types/Generic_CR/Generic_CR.zip | Bin 0 -> 678 bytes .../tosca/heat-types/Generic_VF/Generic_VF.zip | Bin 460 -> 462 bytes .../import/tosca/heat-types/extVl/extVl.zip | Bin 762 -> 767 bytes .../heat-types/forwardingPath/forwardingPath.json | 21 + .../heat-types/forwardingPath/forwardingPath.yml | 24 + .../heat-types/forwardingPath/forwardingPath.zip | Bin 0 -> 509 bytes .../tosca/heat-types/globalPort/globalPort.yml | 2 + .../tosca/heat-types/globalPort/globalPort.zip | Bin 1245 -> 1183 bytes .../import/tosca/policy-types/policyTypes.yml | 35 +- .../import/tosca/policy-types/policyTypes.zip | Bin 673 -> 905 bytes .../tosca/relationship-types/relationshipTypes.yml | 5 +- .../tosca/relationship-types/relationshipTypes.zip | Bin 1396 -> 1421 bytes .../scripts/import/tosca/importCategoryTypes.py | 37 +- .../scripts/import/tosca/importDataTypes.py | 37 +- .../scripts/import/tosca/importGroupTypes.py | 37 +- .../scripts/import/tosca/importHeatTypes.py | 39 +- .../scripts/import/tosca/importNodeType.py | 18 +- .../scripts/import/tosca/importNormativeAll.py | 51 +- .../import/tosca/importNormativeCapabilities.py | 37 +- .../import/tosca/importNormativeElements.py | 30 +- .../importNormativeInterfaceLifecycleTypes.py | 37 +- .../importNormativeNoHeatAndNormativeTypes.py | 43 +- .../scripts/import/tosca/importNormativeTypes.py | 46 +- .../scripts/import/tosca/importONAPNormativeAll.py | 27 +- .../scripts/import/tosca/importOnapTypes.py | 35 +- .../scripts/import/tosca/importPolicyTypes.py | 37 +- .../scripts/import/tosca/importUsersFromYaml.py | 63 +- .../scripts/import/tosca/typesToUpgrade.json | 15 +- .../import/tosca/upgradeHeatAndNormativeTypes.py | 37 +- .../scripts/import/tosca/upgradeHeatTypes1707.py | 37 +- .../scripts/import/tosca/upgradeNormative.py | 51 +- .../import/tosca/upgradeNormativeVersion.py | 39 +- .../import/tosca/upgradeNormativeVersionAll.py | 13 +- .../tosca/upgradeNormativeVersionProd1702_3537.py | 49 +- .../scripts/import/tosca/upgradeONAPNormative.py | 21 +- catalog-be/src/main/webapp/WEB-INF/web.xml | 14 +- .../org/openecomp/sdc/AuditingMockManager.java | 44 - .../org/openecomp/sdc/ElementOperationMock.java | 447 +- .../org/openecomp/sdc/ErrorConfigurationTest.java | 56 +- .../openecomp/sdc/TestExternalConfiguration.java | 40 +- .../src/test/java/org/openecomp/sdc/ZipUtil.java | 132 +- .../sdc/be/DummyConfigurationManager.java | 4 +- .../auditing/impl/AuditBaseEventFactoryTest.java | 132 + .../auditing/impl/AuditConsumerEventFuncTest.java | 200 + .../sdc/be/auditing/impl/AuditTestUtils.java | 236 + .../impl/category/AuditCategoryEventFuncTest.java | 127 + .../distribution/AuditDistrEngineFuncTest.java | 191 + .../impl/distribution/AuditDistrEventFuncTest.java | 387 + .../impl/ecompopenv/AuditEcompOpEnvEventTest.java | 156 + .../externalapi/AuditExternalApiEventFuncTest.java | 368 + .../AuditResourceAdminEventFuncTest.java | 432 + .../impl/usersadmin/AuditUserEventFuncTest.java | 395 + .../sdc/be/components/AuditingManagerTest.java | 71 +- .../sdc/be/components/BaseConfDependentTest.java | 48 - .../components/BaseServiceBusinessLogicTest.java | 355 + .../sdc/be/components/BeConfDependentTest.java | 34 + .../be/components/ComponentBusinessLogicTest.java | 157 +- .../sdc/be/components/GroupBusinessLogicTest.java | 379 +- .../components/HealthCheckBusinessLogicTest.java | 82 +- .../org/openecomp/sdc/be/components/PathTest.java | 143 + .../be/components/PropertyBusinessLogicTest.java | 319 +- .../be/components/ResourceImportManagerTest.java | 608 +- .../sdc/be/components/ResourceTestUtils.java | 112 +- .../be/components/ServiceBusinessLogicTest.java | 1749 ++- .../be/components/ServiceDistributionBLTest.java | 202 + .../clean/AsdcComponentsCleanerTaskTest.java | 64 - .../engine/AaiMockRequestHandlerTest.java | 48 + .../distribution/engine/CambriaHandlerTest.java | 77 + .../engine/Dev2DevDmaapConsumerTest.java | 91 + .../engine/DistributionEngineConfigTest.java | 198 +- .../engine/DistributionEngineHealthCheckTest.java | 205 +- .../engine/DistributionEngineInitTaskTest.java | 448 +- .../engine/DistributionEngineTest.java | 95 + .../DummyDistributionConfigurationManager.java | 37 + .../engine/EnvironmentsEngineTest.java | 190 + .../distribution/engine/StepsTenantIsolation.java | 310 + .../components/distribution/engine/TestSuite.java | 12 - .../engine/rest/MsoRestClientTest.java | 135 + .../components/impl/ArtifactBusinessLogicTest.java | 661 +- .../be/components/impl/ArtifactResolverTest.java | 21 +- .../impl/CapabilityTypeImportManagerTest.java | 108 +- .../impl/CategoriesImportManagerTest.java | 127 +- .../impl/ComponentInstanceBusinessLogicTest.java | 559 +- .../be/components/impl/ComponentsUtilsTest.java | 402 + .../impl/CompositionBusinessLogicTest.java | 242 +- .../components/impl/CsarValidationUtilsTest.java | 18 +- .../sdc/be/components/impl/ElementBLTest.java | 165 + .../sdc/be/components/impl/ImportUtilsTest.java | 879 +- .../components/impl/InputsBusinessLogicTest.java | 36 +- .../InterfaceLifecycleTypeImportManagerTest.java | 87 +- .../components/impl/PolicyBusinessLogicTest.java | 493 + .../impl/PolicyPropertiesBusinessLogicTest.java | 148 + .../impl/PolicyTypeBusinessLogicTest.java | 110 + .../components/impl/ResourceBusinessLogicTest.java | 3342 ++--- .../impl/ResourceInstanceBusinessLogicTest.java | 497 +- .../impl/generic/GenericTypeBusinessLogicTest.java | 15 +- .../impl/utils/PolicyTypeImportUtilsTest.java | 258 + .../components/impl/utils/TestGenerationUtils.java | 20 + .../version/GroupMembersUpdateOperationTest.java | 152 + .../version/PolicyTargetsUpdateOperationTest.java | 127 + ...PostChangeVersionOperationOrchestratorTest.java | 80 + .../CertificationChangeTransitionTest.java | 266 +- .../lifecycle/CertificationRequestTest.java | 425 +- .../sdc/be/components/lifecycle/CheckinTest.java | 259 +- .../sdc/be/components/lifecycle/CheckoutTest.java | 295 +- .../be/components/lifecycle/LifecycleTestBase.java | 358 +- .../be/components/lifecycle/UndoCheckoutTest.java | 131 +- .../GlobalInputsFilteringBusinessLogicTest.java | 20 +- .../merge/GlobalTypesMergeBusinessLogicTest.java | 17 +- .../components/merge/RelationsComparatorTest.java | 24 +- .../components/merge/TopologyComparatorTest.java | 11 +- .../capability/SimpleCapabilityResolverTest.java | 113 + .../HeatEnvArtifactsMergeBusinessLogicTest.java | 14 +- .../merge/input/ComponentInputsMergeBLTest.java | 19 +- .../InputsValuesMergingBusinessLogicTest.java | 68 +- .../ComponentInstanceArtifactsMergeTest.java | 10 +- ...entInstanceCapabiliteisPropertiesMergeTest.java | 70 + .../ComponentInstanceCapabilitiesMergeBLTest.java | 275 + .../ComponentInstanceHeatEnvMergeTest.java | 19 +- ...omponentInstanceMergeDataBusinessLogicTest.java | 19 +- .../ComponentInstancePropsAndInputsMergeTest.java | 25 +- .../ComponentInstanceRelationMergeTest.java | 378 + .../ComponentInstanceForwardingPathMergeTest.java | 101 + .../ComponentInstanceInputsMergeBLTest.java | 31 +- .../ComponentInstancePropertiesMergeBLTest.java | 25 +- ...aDefinitionsValuesMergingBusinessLogicTest.java | 16 +- .../PropertyDataValueMergeBusinessLogicTest.java | 25 +- .../ResourceDataMergeBusinessLogicTest.java | 65 +- .../merge/utils/MergeInstanceUtilsTest.java | 328 + .../be/components/path/BaseForwardingPathTest.java | 208 + .../path/BaseForwardingPathVersionChangeTest.java | 104 + .../path/ForwardingPathBussinessLogicTest.java | 107 + .../path/ForwardingPathChangeVersionTest.java | 60 + .../path/ForwardingPathDeleteCITest.java | 74 + .../components/path/ForwardingPathTestUtils.java | 23 + .../path/ForwardingPathToscaUtilTest.java | 186 + .../path/ForwardingPathValidatorTest.java | 151 + .../path/beans/ArtifactCassandraDaoMock.java | 15 + .../path/beans/AuditCassandraDaoMock.java | 15 + .../components/path/beans/CassandraClientMock.java | 21 + .../path/beans/ComponentCassandraDaoMock.java | 68 + .../path/beans/DistributionEngineMock.java | 61 + .../path/beans/EnvironmentCassandraDaoMock.java | 15 + .../beans/ForwardingPathToscaOperationFacade.java | 45 + .../path/beans/ForwardingPathValidatorMock.java | 16 + .../path/beans/InMemoryTitanGraphClient.java | 218 + .../path/beans/SdcSchemaFilesCassandraDaoMock.java | 15 + .../components/path/beans/TitanGraphTestSetup.java | 166 + .../be/components/path/utils/GraphTestUtils.java | 115 + .../ComponentInstancePropertyDeceleratorTest.java | 238 + .../property/PolicyPropertyDeceleratorTest.java | 172 + .../property/PropertyDeceleratorTestBase.java | 69 + .../scheduledtasks/RecoveryThreadManagerTest.java | 138 + .../sdc/be/components/utils/ArtifactBuilder.java | 4 +- .../utils/CapabilityDefinitionBuilder.java | 51 + .../sdc/be/components/utils/ComponentBuilder.java | 155 + .../components/utils/ComponentInstanceBuilder.java | 38 +- .../utils/ComponentInstancePropertyBuilder.java | 22 + .../components/utils/GroupDefinitionBuilder.java | 38 + .../sdc/be/components/utils/GroupTypeBuilder.java | 43 + .../sdc/be/components/utils/ObjectGenerator.java | 12 +- .../utils/OperationalEnvironmentBuilder.java | 35 + .../components/utils/PolicyDefinitionBuilder.java | 70 + .../sdc/be/components/utils/PolicyTypeBuilder.java | 84 + .../PropertyDataDefinitionAbstractBuilder.java | 94 + .../utils/PropertyDataDefinitionBuilder.java | 65 +- .../sdc/be/components/utils/RelationsBuilder.java | 14 +- .../sdc/be/components/utils/ResourceBuilder.java | 113 +- .../sdc/be/components/utils/ServiceBuilder.java | 29 + .../sdc/be/components/utils/UtilsTest.java | 53 + .../ServiceDistributionValidationTest.java | 153 + .../org/openecomp/sdc/be/config/SpringConfig.java | 7 + .../be/datamodel/UiComponentDataConverterTest.java | 74 + .../DistributionBusinessLogicTest.java | 477 +- .../ServiceDistributionArtifactsBuilderTest.java | 144 +- .../openecomp/sdc/be/distribution/TestQueue.java | 293 +- .../servlet/DistributionServletTest.java | 219 +- .../sdc/be/ecomp/GenerateEcompErrorFileTest.java | 62 +- .../externalapi/servlet/AssetsDataServletTest.java | 254 +- .../servlet/ExternalRefServletTest.java | 603 + .../openecomp/sdc/be/impl/ComponentsUtilsTest.java | 288 - .../servlets/AbstractValidationsServletTest.java | 117 +- .../sdc/be/servlets/ApplicationConfig.java | 45 +- .../openecomp/sdc/be/servlets/BaseTestConfig.java | 27 + .../be/servlets/ComponentInstanceServletTest.java | 208 +- .../sdc/be/servlets/GroupEndpointTest.java | 179 + .../sdc/be/servlets/GroupTypesEndpointTest.java | 197 + .../sdc/be/servlets/JerseySpringBaseTest.java | 45 + .../sdc/be/servlets/PolicyServletTest.java | 338 + .../sdc/be/servlets/PolicyTypesEndpointTest.java | 101 + .../sdc/be/servlets/ResourceServletTest.java | 419 +- .../sdc/be/servlets/ResourceUploadServletTest.java | 233 +- .../sdc/be/servlets/TypesUploadServletTest.java | 292 +- .../sdc/be/servlets/UserAdminServletTest.java | 340 +- .../tosca/CapabiltyRequirementConvertorTest.java | 124 + .../org/openecomp/sdc/be/tosca/CsarUtilsTest.java | 159 +- .../sdc/be/tosca/PropertyConvertorTest.java | 27 +- .../org/openecomp/sdc/be/tosca/SchemaFiles.java | 84 +- .../sdc/be/tosca/ToscaExportUtilsTest.java | 222 +- .../transaction/mngr/SdncTransactionTest.java | 769 +- .../cucumber/runners/RunTenantIsolationTest.java | 15 + .../test/resources/application-context-test.xml | 17 + .../config/catalog-be/DME2preferredRouter.txt | 0 .../resources/config/catalog-be/configuration.yaml | 67 +- .../distribution-engine-configuration.yaml | 39 +- .../config/catalog-be/error-configuration.yaml | 228 +- .../resources/cucumber/tenantIsolation.feature | 42 + catalog-be/src/test/resources/logback-test.xml | 2 +- .../src/test/resources/paths/elasticsearch.yml | 392 + .../src/test/resources/paths/path-context.xml | 71 + 609 files changed, 89388 insertions(+), 67877 deletions(-) create mode 100644 catalog-be/DME2preferredRouter.txt create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java create mode 100644 catalog-be/src/main/resources/config/DME2preferredRouter.txt create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml create mode 100644 catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java create mode 100644 catalog-be/src/test/resources/application-context-test.xml create mode 100644 catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt create mode 100644 catalog-be/src/test/resources/cucumber/tenantIsolation.feature create mode 100644 catalog-be/src/test/resources/paths/elasticsearch.yml create mode 100644 catalog-be/src/test/resources/paths/path-context.xml (limited to 'catalog-be') diff --git a/catalog-be/DME2preferredRouter.txt b/catalog-be/DME2preferredRouter.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index 1b2a92ddbf..fb966f4402 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -115,25 +115,10 @@ compile - - - org.slf4j - slf4j-api - ${slf4j-api.version} - compile - - ch.qos.logback logback-classic - ${logback.version} - compile - - - - ch.qos.logback - logback-core - ${logback.version} + ${logback.version} compile @@ -141,7 +126,7 @@ org.yaml snakeyaml - ${snakeyaml.version} + ${snakeyaml.version} compile @@ -176,18 +161,60 @@ compile + + org.glassfish.jersey.ext + jersey-spring4 + ${jersey-bom.version} + + + org.springframework + spring-web + + + org.springframework + spring-beans + + + org.springframework + spring-core + + + org.springframework + spring-aop + + + + org.springframework + spring-context + + + + + + + + org.glassfish.hk2.external + asm-all-repackaged + + + + org.glassfish.jersey.ext + jersey-bean-validation + + org.apache.httpcomponents httpclient - ${httpclient.version} + ${httpclient.version} compile org.apache.httpcomponents httpcore - ${httpcore.version} + ${httpcore.version} compile @@ -201,7 +228,7 @@ commons-codec commons-codec - ${commons-codec} + ${commons-codec} compile @@ -209,7 +236,7 @@ javax.servlet servlet-api - ${servlet-api.version} + ${servlet-api.version} provided @@ -351,7 +378,7 @@ org.elasticsearch elasticsearch - ${elastic-search.version} + ${elastic-search.version} compile @@ -384,23 +411,18 @@ compile + + com.att.nsa cambriaClient - 0.0.1 - compile - - - - com.att.nsa - saClientLibrary - 0.0.1 + 1.2.1-oss compile - org.slf4j - slf4j-log4j12 + com.att.nsa + saClientLibrary @@ -520,8 +542,46 @@ compile + + org.onap.dmaap.messagerouter.dmaapclient + dmaapClient + 1.1.1 + compile + + + com.att.aft + dme2 + + + + + com.att.aft + dme2 + 3.1.200-oss + + + + javax.jms + jms + 1.1 + provided + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + org.assertj + assertj-core + test + + + org.glassfish.jersey.test-framework.providers jersey-test-framework-provider-bundle ${jersey-bom.version} @@ -529,17 +589,37 @@ test + + + + + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-bom.version} + + + + + com.github.tomakehurst + wiremock + test + + org.eclipse.jetty jetty-servlet - ${jetty.version} + ${jetty.version} test org.eclipse.jetty jetty-webapp - ${jetty.version} + ${jetty.version} test @@ -553,14 +633,6 @@ org.mockito mockito-core - ${mockito.version} - test - - - - org.assertj - assertj-core - ${assertj.version} test @@ -577,6 +649,18 @@ ${spring.version} test + + + io.cucumber + cucumber-java + test + + + + io.cucumber + cucumber-junit + test + @@ -614,6 +698,41 @@ + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + package + + copy-dependencies + + + compile + + + + copy-installed + install + + copy + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + ${project.packaging} + + + ${project.parent.basedir}/sdc-os-chef/sdc-backend/ + + + + + + com.jcabi jcabi-maven-plugin ${jcabi.plugin.version} @@ -627,6 +746,71 @@ + maven-resources-plugin + 2.6 + + + copy-normatives + install + + copy-resources + + + ${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-normatives/files/default + + + ./target + + normatives.tar.gz + + + + + + + + copy-static-configuration-files + install + + copy-resources + + + ${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default + + + ${project.parent.basedir}/catalog-be/src/main/resources/config + + Artifact-Generator.properties + error-configuration.yaml + ecomp-error-configuration.yaml + logback.xml + + + + + + + + copy-tosca-folder + + install + + copy-resources + + + ${project.parent.basedir}/asdctool/tosca + + + ${project.parent.basedir}/catalog-be/src/main/resources/import/tosca + true + + + + + + + + org.apache.maven.plugins maven-assembly-plugin @@ -691,6 +875,33 @@ + + + clean-static-files + clean + + clean + + + + + + ${project.parent.basedir}/asdctool/tosca + false + + + + ${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default + + Artifact-Generator.properties + error-configuration.yaml + ecomp-error-configuration.yaml + logback.xml + + + + + @@ -753,16 +964,16 @@ - - catalog - - false - - - - ${project.artifactId}-${project.version} - - + + catalog + + false + + + + ${project.artifactId}-${project.version} + + docker-staging @@ -874,7 +1085,7 @@ io.fabric8 docker-maven-plugin - 0.23.0 + ${fabric8.version} true diff --git a/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz b/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz index 873c8e00ce..474e9c70ae 100644 Binary files a/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz and b/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz differ diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb index 825dd54061..9bb4c33dec 100644 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb @@ -659,3 +659,56 @@ environmentContext: - Needed_Non-Revenue - Useful_Non-Revenue - General_Non-Revenue + +dmaapConsumerConfiguration: + hosts: olsd004.wnsnet.attws.com:3905 + consumerGroup: asdc + consumerId: mama + timeoutMs: 15000 + limit: 1 + pollingInterval: 2 + topic: com.att.sdc.23911-SDCforTestDev-v001 + latitude: 32.109333 + longitude: 34.855499 + version: 1.0 + serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events + environment: TEST + partner: BOT_R + routeOffer: MR1 + protocol: https + contenttype: application/json + dme2TraceOn: true + aftEnvironment: AFTUAT + aftDme2ConnectionTimeoutMs: 15000 + aftDme2RoundtripTimeoutMs: 240000 + aftDme2ReadTimeoutMs: 50000 + dme2preferredRouterFilePath: DME2preferredRouter.txt + timeLimitForNotificationHandleMs: 120000 + credential: + username: m09875@sdc.att.com + password: hmXYcznAljMSisdy8zgcag== + +dmeConfiguration: + dme2Search: DME2SEARCH + dme2Resolve: DME2RESOLVE + +excludedPolicyTypesMapping: + # VF: + # - a.b.c + # - c.d.e + #CR: + # - x.y.z + +excludedGroupTypesMapping: + CR: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root + VF: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root + Service: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root \ No newline at end of file diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb index 3491035fcf..f85ce4acde 100644 --- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb +++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb @@ -43,4 +43,40 @@ createTopic: startDistributionEngine: true #This is false by default, since ONAP Dmaap currently doesn't support https -useHttpsWithDmaap: false \ No newline at end of file +useHttpsWithDmaap: false +opEnvRecoveryIntervalSec: 180 +allowedTimeBeforeStaleSec: 300 + +aaiConfig: + httpRequestConfig: + serverRootUrl: https://aai-uint3.test.att.com:8443 + resourceNamespaces: + operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments + + httpClientConfig: + timeouts: + readTimeoutMs: 5000 + connectTimeoutMs: 1000 + clientCertificate: + keyStore: /opt/app/jetty/base/be/etc/non-prod.jks + keyStorePassword: hmXYcznAljMSisdy8zgcag== + headers: + X-FromAppId: asdc + numOfRetries: 3 + +msoConfig: + httpRequestConfig: + serverRootUrl: http://127.0.0.1:8080/onap/mso/infra/modelDistributions/v1 + resourceNamespaces: + distributions: /distributions + + httpClientConfig: + timeouts: + readTimeoutMs: 2000 + connectTimeoutMs: 500 + basicAuthorization: + userName: asdc + password: OTLEp5lfVhYdyw5EAtTUBQ== + numOfRetries: 3 + +currentArtifactInstallationTimeout: 120 diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java new file mode 100644 index 0000000000..eed347f781 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.api; + +import org.javatuples.Pair; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; + +import java.util.List; + +public interface AuditEventFactory { + + String getLogMessage(); + AuditingGenericEvent getDbEvent(); + List> getQueryParams(); + + //TODO remove together with ES related code + String getAuditingEsType(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java deleted file mode 100644 index b6cd4320f4..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.auditing.api; - -import java.util.EnumMap; - -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; - -public interface IAuditingManager { - void auditEvent(EnumMap auditingFields); -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java new file mode 100644 index 0000000000..b68ee0db23 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuthEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAuthRequestEventFactory extends AuditBaseEventFactory { + + private final static String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\""; + + final private AuthEvent event; + + public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus) { + super(AuditingActionEnum.AUTH_REQUEST); + event = new AuthEvent(getAction().getName(), commonFields, authUser, authUrl, realm, authStatus); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getUrl(), event.getUser(), event.getAuthStatus(), event.getRealm()); + } + + + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java new file mode 100644 index 0000000000..8636c1b01d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.apache.commons.lang.StringUtils; +import org.javatuples.Pair; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.api.Constants; + +import java.util.Collections; +import java.util.List; + +public abstract class AuditBaseEventFactory implements AuditEventFactory { + + //TODO imanzon: Check if requestId and serviceInstanceId fields are required for all tables. + //Currently they are included even if they ahs null value. If they should not appear then + //createTable code should be updated so that they need to be removed from the tables + private AuditingActionEnum action; + + public AuditBaseEventFactory(AuditingActionEnum action) { + this.action = action; + } + + public AuditingActionEnum getAction() { + return action; + } + + public static String buildUserNameExtended(User user) { + if (user == null) { + return null; + } + + StringBuilder builder = new StringBuilder(); + appendIfNotEmpty(user.getUserId(), builder); + + String firstName = replaceNullNameWithEmpty(user.getFirstName()); + String lastName = replaceNullNameWithEmpty(user.getLastName()); + + if (appendIfNotEmpty(firstName, builder)) { + appendIfNotEmpty(lastName, builder, " "); + } + else { + appendIfNotEmpty(lastName, builder); + } + appendIfNotEmpty(user.getEmail(), builder); + appendIfNotEmpty(user.getRole(), builder); + + return builder.toString(); + } + + private static boolean appendIfNotEmpty(String value, StringBuilder builder) { + return appendIfNotEmpty(value, builder, ", "); + } + + protected static boolean appendIfNotEmpty(String value, StringBuilder builder, String delimiter) { + if (StringUtils.isEmpty(value)) { + return false; + } + addDelimiterIfNeeded(builder, delimiter); + builder.append(value); + return true; + } + + private static void addDelimiterIfNeeded(StringBuilder builder, String delimiter) { + if (builder.length() > 0) { + builder.append(delimiter); + } + } + + protected static String buildUserName(User user) { + if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) { + return Constants.EMPTY_STRING; + } + StringBuilder sb = new StringBuilder(); + String firstName = replaceNullNameWithEmpty(user.getFirstName()); + if (!firstName.isEmpty()) { + sb.append(firstName); + sb.append(" "); + } + String lastName = replaceNullNameWithEmpty(user.getLastName()); + if (!lastName.isEmpty()) { + sb.append(lastName); + } + sb.append("(").append(user.getUserId()).append(")"); + return sb.toString(); + } + + public static String buildValue(String value) { + if (value == null) { + return Constants.EMPTY_STRING; + } + return value; + } + + protected static String replaceNullNameWithEmpty(String name) { + if (name != null && !name.trim().contains(Constants.NULL_STRING)) { + return name; + } + return Constants.EMPTY_STRING; + } + + @Override + //TODO implement in derived classes for ci testing + public List> getQueryParams() { + return Collections.emptyList(); + } + + @Override + public String getAuditingEsType() { + return this.action.getAuditingEsType(); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java new file mode 100644 index 0000000000..01c82e88da --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.model.ConsumerDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditConsumerEventFactory extends AuditBaseEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" ECOMP_USER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + private final ConsumerEvent event; + + public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, ConsumerDefinition ecompUser) { + super(action); + event = new ConsumerEvent(getAction().getName(), commonFields, buildConsumerName(ecompUser), buildUserName(modifier)); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + + + static String buildConsumerName(ConsumerDefinition consumer) { + StringBuilder ecompUser = new StringBuilder(); + if (consumer != null) { + appendIfNotEmpty(consumer.getConsumerName(), ecompUser, ","); + appendIfNotEmpty(consumer.getConsumerSalt(), ecompUser, ","); + appendIfNotEmpty(consumer.getConsumerPassword(), ecompUser, ","); + } + return ecompUser.toString(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java new file mode 100644 index 0000000000..95dddec3ad --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; + +public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory { + private static final String LOG_STR = "ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ID = \"%s\"" + + " OPERATIONAL_ENVIRONMENT_NAME = \"%s\" OPERATIONAL_ENVIRONMENT_TYPE = \"%s\" TENANT_CONTEXT = \"%s\""; + + private final EcompOperationalEnvironmentEvent event; + + public AuditEcompOpEnvEventFactory(AuditingActionEnum action, String operationalEnvironmentId, String operationalEnvironmentName, + String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) { + super(action); + event = new EcompOperationalEnvironmentEvent(getAction().getName(), operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, operationalEnvironmentAction, tenantContext); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getOperationalEnvironmentAction()), + buildValue(event.getOperationalEnvironmentId()), buildValue(event.getOperationalEnvironmentName()), + buildValue(event.getOperationalEnvironmentType()), buildValue(event.getTenantContext())); + } + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java new file mode 100644 index 0000000000..3400016ff0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditArtifactResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCertificationResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCreateUpdateResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeRequestResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeResourceAdminEventFactory; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditResourceEventFactoryMananger { + + + public static AuditBaseEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + AuditBaseEventFactory factory = null; + + switch (action) { + case IMPORT_RESOURCE: + factory = new AuditImportResourceAdminEventFactory(commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + break; + case CREATE_RESOURCE: + case UPDATE_RESOURCE_METADATA: + factory = new AuditCreateUpdateResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING); + break; + case CHECKIN_RESOURCE: + case CHECKOUT_RESOURCE: + case UNDO_CHECKOUT_RESOURCE: + case CERTIFICATION_REQUEST_RESOURCE: + case START_CERTIFICATION_RESOURCE: + case CERTIFICATION_SUCCESS_RESOURCE: + case FAIL_CERTIFICATION_RESOURCE: + case CANCEL_CERTIFICATION_RESOURCE: + factory = new AuditCertificationResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + case ARTIFACT_UPLOAD: + case ARTIFACT_DELETE: + case ARTIFACT_METADATA_UPDATE: + case ARTIFACT_PAYLOAD_UPDATE: + case ARTIFACT_DOWNLOAD: + factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; +// case DOWNLOAD_ARTIFACT: +// factory = new AuditDownloadArtifactExternalApiEventFactory(commonFields, String resourceType, String resourceName, +// String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, +// String invariantUuid, User modifier, String artifactData); +// break; + case DISTRIBUTION_STATE_CHANGE_REQUEST: + factory = new AuditDistStateChangeRequestResourceAdminEventFactory(commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + case DISTRIBUTION_STATE_CHANGE_APPROV: + case DISTRIBUTION_STATE_CHANGE_REJECT: + factory = new AuditDistStateChangeResourceAdminEventFactory(action, commonFields, prevParams, currParams, + resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did); + break; + default: + throw new UnsupportedOperationException(); + } + return factory; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java index ed0fd6de0e..69c4eb82a0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java @@ -24,276 +24,301 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; class AuditingLogFormatConstants { - private AuditingLogFormatConstants() {} - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME}; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, - AuditingFieldsKeysEnum.AUDIT_STATUS - }; - - static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, - AuditingFieldsKeysEnum.AUDIT_STATUS - }; - - static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT - }; - - static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE - - }; - - static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_USER_UID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_UID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_AUTH_URL, - AuditingFieldsKeysEnum.AUDIT_AUTH_USER, - AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, - AuditingFieldsKeysEnum.AUDIT_AUTH_REALM - }; - - static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, - AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, - AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_DETAILS, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, - AuditingFieldsKeysEnum.AUDIT_USER_AFTER, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - - AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_DESC - }; - - static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { - AuditingFieldsKeysEnum.AUDIT_ACTION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, - AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, - AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, - - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, - AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, - - AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, - AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, - AuditingFieldsKeysEnum.AUDIT_STATUS, - AuditingFieldsKeysEnum.AUDIT_DESC - }; + private AuditingLogFormatConstants() {} + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME}; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, +// AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, - check if required + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID + }; + + static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, + AuditingFieldsKeysEnum.AUDIT_STATUS + }; + + static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, + AuditingFieldsKeysEnum.AUDIT_STATUS + }; + + static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={ + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT + }; + + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE + + }; + + static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_USER_UID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_UID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_AUTH_URL, + AuditingFieldsKeysEnum.AUDIT_AUTH_USER, + AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, + AuditingFieldsKeysEnum.AUDIT_AUTH_REALM + }; + + static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, + AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, + AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_DETAILS, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, + AuditingFieldsKeysEnum.AUDIT_USER_AFTER, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static AuditingFieldsKeysEnum[] ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME, + AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE, + AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static AuditingFieldsKeysEnum[] EXTERNAL_ACTIVATE_SERVICE_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_DESC + }; + + static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = { + AuditingFieldsKeysEnum.AUDIT_ACTION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, + AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, + AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, + + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, + AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, + + AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, + AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, + AuditingFieldsKeysEnum.AUDIT_STATUS, + AuditingFieldsKeysEnum.AUDIT_DESC + }; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java index 8fb5c4116e..ee4b70c0f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.auditing.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.Formatter; -import java.util.Locale; - import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -34,240 +28,269 @@ import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Formatter; +import java.util.Locale; +import java.util.Map; + public class AuditingLogFormatUtil { - // When adding any new fields here, please keep the convention = - // , with the space between them. - private static Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class.getName()); - - // This is the key by which audit marker is recognized in logback.xml - private static String AUDIT_MARKER_STR = "AUDIT_MARKER"; - - public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); - - protected static void logAuditEvent(EnumMap auditingFields) { - - StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb, Locale.US); - log.trace("logAuditEvent - start"); - - try { - - // Common fields - String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); - Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - String status = null; - if (statusObj != null) { - status = String.valueOf(statusObj); - } - String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); - String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); - - AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action); - StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType); - String formattedString = formattedEvent.toString(); - - // This is the only way to fix DE166225 without major refactoring, - // after it was previously agreed with Ella that activity type will - // be the method name. - - if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) { - HttpRequestAuthentication(formattedString); - } else { - log.info(auditMarker, formattedString); - } - } catch (Exception e) { - log.debug("unexpected error occurred: {}", e.getMessage(), e); - - } finally { - formatter.close(); - log.trace("logAuditEvent - end"); - } - - } - - private static void HttpRequestAuthentication(String formattedString) { - log.info(auditMarker, formattedString); - } - - private static StringBuilder getFormattedEvent(EnumMap auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) { - - StringBuilder formattedString = new StringBuilder(); - - switch (auditEventType) { - case ADD_USER: - case DELETE_USER: - case UPDATE_USER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields); - - break; - case USER_ACCESS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_REGISTER: - case DISTRIBUTION_UN_REGISTER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields); - break; - case UPDATE_RESOURCE_METADATA: - case CREATE_RESOURCE: - case IMPORT_RESOURCE: - ArrayList createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); - createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); - if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) { - createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE); - } - AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100]; - createResourceArray = createResourceList.toArray(createResourceArray); - formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields); - break; - case CHECKIN_RESOURCE: - case CHECKOUT_RESOURCE: - case UNDO_CHECKOUT_RESOURCE: - case CERTIFICATION_REQUEST_RESOURCE: - case START_CERTIFICATION_RESOURCE: - case CERTIFICATION_SUCCESS_RESOURCE: - case FAIL_CERTIFICATION_RESOURCE: - case CANCEL_CERTIFICATION_RESOURCE: - ArrayList checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); - checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); - checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); - AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100]; - checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray); - String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); - if (comment == null || comment.equals(Constants.NULL_STRING)) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING); - } - formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields); - break; - case ARTIFACT_UPLOAD: - case ARTIFACT_DELETE: - case ARTIFACT_METADATA_UPDATE: - case ARTIFACT_PAYLOAD_UPDATE: - case ARTIFACT_DOWNLOAD: - ArrayList artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ; - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); - artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); - artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case DOWNLOAD_ARTIFACT: - ArrayList downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case DISTRIBUTION_STATE_CHANGE_REQUEST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields); - break; - case DISTRIBUTION_STATE_CHANGE_APPROV: - case DISTRIBUTION_STATE_CHANGE_REJECT: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields); - break; - case CREATE_DISTRIBUTION_TOPIC: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_KEY_TO_TOPIC_ACL: - case REMOVE_KEY_FROM_TOPIC_ACL: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_STATUS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields); - break; - case DISTRIBUTION_NOTIFY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields); - break; - case DISTRIBUTION_DEPLOY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields); - break; - case GET_UEB_CLUSTER: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields); - break; - case DISTRIBUTION_ARTIFACT_DOWNLOAD: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields); - break; - case AUTH_REQUEST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_ECOMP_USER_CREDENTIALS: - case GET_ECOMP_USER_CREDENTIALS: - case DELETE_ECOMP_USER_CREDENTIALS: - case UPDATE_ECOMP_USER_CREDENTIALS: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields); - break; - case ADD_CATEGORY: - case ADD_SUB_CATEGORY: - case ADD_GROUPING: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields); - break; - case GET_USERS_LIST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields); - break; - case GET_CATEGORY_HIERARCHY: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields); - break; - case GET_ASSET_LIST: - case GET_FILTERED_ASSET_LIST: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields); - break; - case GET_ASSET_METADATA: - case GET_TOSCA_MODEL: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields); - break; - case ARTIFACT_UPLOAD_BY_API: - case ARTIFACT_DELETE_BY_API: - case ARTIFACT_UPDATE_BY_API: - ArrayList uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY)); - AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; - artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray); - formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); - break; - case CREATE_RESOURCE_BY_API: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields); - break; - case CHANGE_LIFECYCLE_BY_API: - formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields); - break; - default: - break; - } - - return formattedString; - } - - private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, EnumMap auditingFields) { - StringBuilder formattedString = new StringBuilder(); - for (int i = 0; i < sortedFieldsArray.length; i++) { - AuditingFieldsKeysEnum key = sortedFieldsArray[i]; - - Object fieldVal = auditingFields.get(key); - if (fieldVal != null) { - formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\""); - if (i < sortedFieldsArray.length - 1) { - formattedString.append(" "); - } - } - } - return formattedString; - } - - protected static String getModifier(String modifierName, String modifierUid) { - if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) { - return Constants.EMPTY_STRING; - } - StringBuilder sb = new StringBuilder(); - if (modifierName != null) { - sb.append(modifierName); - } - sb.append("(").append(modifierUid).append(")"); - return sb.toString(); - } - - protected static String getUser(String userData) { - StringBuilder sb = new StringBuilder(); - sb.append(userData); - return sb.toString(); - } + // When adding any new fields here, please keep the convention = + // , with the space between them. + private static final Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class); + + // This is the key by which audit marker is recognized in logback.xml + private static String AUDIT_MARKER_STR = "AUDIT_MARKER"; + + public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR); + + protected static String logAuditEvent(Map auditingFields) { + + StringBuilder sb = new StringBuilder(); + Formatter formatter = new Formatter(sb, Locale.US); + log.trace("logAuditEvent - start"); + + String formattedString = ""; + + try { + + // Common fields + String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); + Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + String status = null; + if (statusObj != null) { + status = String.valueOf(statusObj); + } + String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC); + String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION); + + AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action); + StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType); + formattedString = formattedEvent.toString(); + + // This is the only way to fix DE166225 without major refactoring, + // after it was previously agreed with Ella that activity type will + // be the method name. + + if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) { + HttpRequestAuthentication(formattedString); + } else { + log.info(auditMarker, formattedString); + } + } catch (Exception e) { + log.debug("unexpected error occurred: {}", e.getMessage(), e); + + } finally { + formatter.close(); + log.trace("logAuditEvent - end"); + } + return formattedString; + + } + + protected static void logAuditEvent(final String formattedString) { + log.trace("logAuditEvent - start"); + log.info(auditMarker, formattedString); + log.trace("logAuditEvent - end"); + } + + + private static void HttpRequestAuthentication(String formattedString) { + log.info(auditMarker, formattedString); + } + + private static StringBuilder getFormattedEvent(Map auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) { + + StringBuilder formattedString = new StringBuilder(); + + switch (auditEventType) { + case ADD_USER: + case DELETE_USER: + case UPDATE_USER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields); + + break; + case USER_ACCESS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_REGISTER: + case DISTRIBUTION_UN_REGISTER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields); + break; + case UPDATE_RESOURCE_METADATA: + case CREATE_RESOURCE: + case IMPORT_RESOURCE: + ArrayList createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); + createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); + if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) { + createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE); + } + AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100]; + createResourceArray = createResourceList.toArray(createResourceArray); + formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields); + break; + case CHECKIN_RESOURCE: + case CHECKOUT_RESOURCE: + case UNDO_CHECKOUT_RESOURCE: + case CERTIFICATION_REQUEST_RESOURCE: + case START_CERTIFICATION_RESOURCE: + case CERTIFICATION_SUCCESS_RESOURCE: + case FAIL_CERTIFICATION_RESOURCE: + case CANCEL_CERTIFICATION_RESOURCE: + ArrayList checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)); + checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); + checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY)); + AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100]; + checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray); + String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT); + if (comment == null || comment.equals(Constants.NULL_STRING)) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING); + } + formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields); + break; + case ARTIFACT_UPLOAD: + case ARTIFACT_DELETE: + case ARTIFACT_METADATA_UPDATE: + case ARTIFACT_PAYLOAD_UPDATE: + case ARTIFACT_DOWNLOAD: + ArrayList artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ; + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID); + artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA); + artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case DOWNLOAD_ARTIFACT: + ArrayList downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case DISTRIBUTION_STATE_CHANGE_REQUEST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields); + break; + case DISTRIBUTION_STATE_CHANGE_APPROV: + case DISTRIBUTION_STATE_CHANGE_REJECT: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields); + break; + case CREATE_DISTRIBUTION_TOPIC: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_KEY_TO_TOPIC_ACL: + case REMOVE_KEY_FROM_TOPIC_ACL: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_STATUS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields); + break; + case DISTRIBUTION_NOTIFY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields); + break; + case DISTRIBUTION_DEPLOY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields); + break; + case GET_UEB_CLUSTER: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields); + break; + case DISTRIBUTION_ARTIFACT_DOWNLOAD: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields); + break; + case AUTH_REQUEST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_ECOMP_USER_CREDENTIALS: + case GET_ECOMP_USER_CREDENTIALS: + case DELETE_ECOMP_USER_CREDENTIALS: + case UPDATE_ECOMP_USER_CREDENTIALS: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields); + break; + case ADD_CATEGORY: + case ADD_SUB_CATEGORY: + case ADD_GROUPING: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields); + break; + case GET_USERS_LIST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields); + break; + case GET_CATEGORY_HIERARCHY: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields); + break; + case GET_ASSET_LIST: + case GET_FILTERED_ASSET_LIST: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields); + break; + case GET_ASSET_METADATA: + case GET_TOSCA_MODEL: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields); + break; + case ARTIFACT_UPLOAD_BY_API: + case ARTIFACT_DELETE_BY_API: + case ARTIFACT_UPDATE_BY_API: + ArrayList uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY)); + AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100]; + artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray); + formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields); + break; + case CREATE_RESOURCE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields); + break; + case CHANGE_LIFECYCLE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields); + break; + case ACTIVATE_SERVICE_BY_API: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_ACTIVATE_SERVICE_ARRAY, auditingFields); + break; + case CREATE_ENVIRONMENT: + case UPDATE_ENVIRONMENT: + case DELETE_ENVIRONMENT: + case UNKNOWN_ENVIRONMENT_NOTIFICATION: + case UNSUPPORTED_ENVIRONMENT_TYPE: + formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY, auditingFields); + break; + default: + break; + } + + return formattedString; + } + + private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, Map auditingFields) { + StringBuilder formattedString = new StringBuilder(); + for (int i = 0; i < sortedFieldsArray.length; i++) { + AuditingFieldsKeysEnum key = sortedFieldsArray[i]; + + Object fieldVal = auditingFields.get(key); + if (fieldVal != null) { + formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\""); + if (i < sortedFieldsArray.length - 1) { + formattedString.append(" "); + } + } + } + return formattedString; + } + + protected static String getModifier(String modifierName, String modifierUid) { + if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) { + return Constants.EMPTY_STRING; + } + StringBuilder sb = new StringBuilder(); + if (modifierName != null) { + sb.append(modifierName); + } + sb.append("(").append(modifierUid).append(")"); + return sb.toString(); + } + + protected static String getUser(String userData) { + StringBuilder sb = new StringBuilder(); + sb.append(userData); + return sb.toString(); + } + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java index aa5afa4a8e..19eab0a409 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.auditing.impl; -import java.util.EnumMap; -import java.util.Map.Entry; - -import javax.annotation.Resource; - -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -39,99 +34,134 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -@Component("auditingManager") -public class AuditingManager implements IAuditingManager { - - private static Logger log = LoggerFactory.getLogger(AuditingManager.class.getName()); - - @Resource - private AuditingDao auditingDao; - @Autowired - private AuditCassandraDao cassandraDao; - - @Override - public void auditEvent(EnumMap auditingFields) { - try { - boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit(); - if (disableAudit) { - return; - } - // Adding UUID from thread local - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid()); - - Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status)); - - // normalizing empty string values - US471661 - normalizeEmptyAuditStringValues(auditingFields); - - // Format modifier - formatModifier(auditingFields); - - // Format user - formatUser(auditingFields); - - // Logging the event - AuditingLogFormatUtil.logAuditEvent(auditingFields); - - // Determining the type of the auditing data object - AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType()); - ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType()); - if (!addRecordStatus.equals(ActionStatus.OK)) { - log.warn("Failed to persist auditing event: {}", addRecordStatus.name()); - } - - AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields); - if (recordForCassandra != null) { - CassandraOperationStatus result = cassandraDao.saveRecord(recordForCassandra); - if (!result.equals(CassandraOperationStatus.OK)) { - log.warn("Failed to persist to cassandra auditing event: {}", addRecordStatus.name()); - } - } - - } catch (Exception e) { - // Error during auditing shouldn't terminate flow - log.warn("Error during auditEvent: {}", e); - } - } - - private void formatUser(EnumMap auditingFields) { - if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) { - String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID); - - String user = AuditingLogFormatUtil.getUser(userDetails); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user); - } - } - - private void formatModifier(EnumMap auditingFields) { - String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier); - auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME); - } - - private void normalizeEmptyAuditStringValues(EnumMap auditingFields) { - for (Entry auditingEntry : auditingFields.entrySet()) { - if (auditingEntry.getKey().getValueClass().equals(String.class)) { - String auditingValue = (String) auditingEntry.getValue(); - boolean isEmpty = false; - if (auditingValue != null) { - String trimmedValue = auditingValue.trim(); - if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) { - isEmpty = true; - } - } else {// is null - isEmpty = true; - } - // Normalizing to "" - if (isEmpty) { - auditingEntry.setValue(Constants.EMPTY_STRING); - } - } - } - } +import java.util.Map; +import java.util.Map.Entry; + +@Component +public class AuditingManager { + + private static final Logger log = LoggerFactory.getLogger(AuditingManager.class); + private final AuditingDao auditingDao; + private final AuditCassandraDao cassandraDao; + + public AuditingManager(AuditingDao auditingDao, AuditCassandraDao cassandraDao) { + this.auditingDao = auditingDao; + this.cassandraDao = cassandraDao; + } + + // TODO remove after completing refactoring + public String auditEvent(Map auditingFields) { + String msg = ""; + try { + boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit(); + if (disableAudit) { + return null; + } + // Adding UUID from thread local + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid()); + + Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status)); + + // normalizing empty string values - US471661 + normalizeEmptyAuditStringValues(auditingFields); + + // Format modifier + formatModifier(auditingFields); + + // Format user + formatUser(auditingFields); + + // Logging the event + msg = AuditingLogFormatUtil.logAuditEvent(auditingFields); + + // Determining the type of the auditing data object + AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); + log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType()); + ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType()); + if (!addRecordStatus.equals(ActionStatus.OK)) { + log.warn("Failed to persist auditing event: {}", addRecordStatus); + } + + AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields); + if (recordForCassandra != null) { + saveEventToCassandra(recordForCassandra); + } + + } catch (Exception e) { + // Error during auditing shouldn't terminate flow + log.warn("Error during auditEvent: {}", e); + } + return msg; + } + + + public String auditEvent(AuditEventFactory factory) { + if (ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit()) { + return null; + } + AuditingGenericEvent event = factory.getDbEvent(); + // Logging the event + //TODO - change this call after EELF Audit stuff merge + String msg = factory.getLogMessage(); + AuditingLogFormatUtil.logAuditEvent(msg); + + //TODO - remove this method after we got rid of ES + saveEventToElasticSearch(factory, event); + saveEventToCassandra(event); + return msg; + } + + private void saveEventToCassandra(AuditingGenericEvent event) { + CassandraOperationStatus result = cassandraDao.saveRecord(event); + if (!result.equals(CassandraOperationStatus.OK)) { + log.warn("Failed to persist to cassandra auditing event: {}", result.name()); + } + } + + private void saveEventToElasticSearch(AuditEventFactory factory, AuditingGenericEvent event) { + ActionStatus addRecordStatus = auditingDao.addRecord(event, factory.getAuditingEsType()); + if (!addRecordStatus.equals(ActionStatus.OK)) { + log.warn("Failed to persist auditing event: {}", addRecordStatus.name()); + } + } + + + private void formatUser(Map auditingFields) { + if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) { + String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID); + + String user = AuditingLogFormatUtil.getUser(userDetails); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user); + } + } + + private void formatModifier(Map auditingFields) { + String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID)); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier); + auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME); + } + + private void normalizeEmptyAuditStringValues(Map auditingFields) { + for (Entry auditingEntry : auditingFields.entrySet()) { + if (auditingEntry.getKey().getValueClass().equals(String.class)) { + String auditingValue = (String) auditingEntry.getValue(); + boolean isEmpty = false; + if (auditingValue != null) { + String trimmedValue = auditingValue.trim(); + if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) { + isEmpty = true; + } + } else {// is null + isEmpty = true; + } + // Normalizing to "" + if (isEmpty) { + auditingEntry.setValue(Constants.EMPTY_STRING); + } + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java new file mode 100644 index 0000000000..84c3a0392d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddCategoryEventFactory(CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java new file mode 100644 index 0000000000..6ee7624ddf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddGroupingCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddGroupingCategoryEventFactory(CommonAuditData commonFields, User modifier, String categoryName, + String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_GROUPING, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java new file mode 100644 index 0000000000..241d0c0fc5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddSubCategoryEventFactory extends AuditCategoryEventFactory { + + public AuditAddSubCategoryEventFactory(CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(AuditingActionEnum.ADD_SUB_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java new file mode 100644 index 0000000000..9a2d7b09a8 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditCategoryEventFactory extends AuditBaseEventFactory { + + private final CategoryEvent event; + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\"" + + " GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(), + event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, + String categoryName, String subCategoryName, String groupingName, String resourceType) { + super(action); + event = new CategoryEvent(getAction().getName(), commonFields, buildUserName(modifier), categoryName, + subCategoryName, groupingName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java new file mode 100644 index 0000000000..8c4de3c43d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetCategoryHierarchyEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory { + + private final GetCategoryHierarchyEvent event; + + protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditGetCategoryHierarchyEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, String details) { + super(action); + event = new GetCategoryHierarchyEvent(getAction().getName(), commonFields, buildUserName(modifier), details); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..907d73546f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditAddKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory { + + public AuditAddKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..5ad7380051 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditAddRemoveKeyDistribEngineEventFactory extends AuditDistribEngineEventFactory{ + + private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " + + "API_KEY = \"%s\" STATUS = \"%s\""; + + public AuditAddRemoveKeyDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic()); + return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName, + event.getRole(), event.getApiKey(), event.getStatus()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java new file mode 100644 index 0000000000..7825cca0e9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditCreateTopicDistribEngineEventFactory extends AuditDistribEngineEventFactory{ + + private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" STATUS = \"%s\""; + + public AuditCreateTopicDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic()); + return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName, event.getStatus()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java new file mode 100644 index 0000000000..cb86f5059c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditDistribDeployEventFactory extends AuditBaseEventFactory { + + private DistributionDeployEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " + + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getCurrVersion(), event.getModifier(), event.getDid(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribDeployEventFactory(CommonAuditData commonFields, String currentVersion, + String did, User modifier, String resourceName, String resourceType) { + + super(AuditingActionEnum.DISTRIBUTION_DEPLOY); + this.event = new DistributionDeployEvent(getAction().getName(), commonFields, did, buildUserName(modifier), + currentVersion, resourceName, resourceType); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java new file mode 100644 index 0000000000..e8453b1d0b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; + +public class AuditDistribDownloadEventFactory extends AuditBaseEventFactory { + + private DistributionDownloadEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDistribDownloadEventFactory(CommonAuditData commonFields, DistributionData distributionData) { + + super(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD); + this.event = new DistributionDownloadEvent(getAction().getName(), commonFields, distributionData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceUrl(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java new file mode 100644 index 0000000000..3ebacb49d9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditDistribEngineEventFactory extends AuditBaseEventFactory{ + + protected final DistributionEngineEvent event; + + public AuditDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(action); + event = new DistributionEngineEvent(getAction().getName(), commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java new file mode 100644 index 0000000000..80c4590b8d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java @@ -0,0 +1,39 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; + +public class AuditDistribNotificationEventFactory extends AuditBaseEventFactory { + + private DistributionNotificationEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " + + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\" DID = \"%s\" " + + "TOPIC_NAME = \"%s\" STATUS = \"%s\" DESC = \"%s\" TENANT = \"%s\" VNF_WORKLOAD_CONTEXT = \"%s\" ENV_ID = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), + event.getCurrVersion(), event.getModifier(), event.getCurrState(), event.getDid(), event.getTopicName(), event.getStatus(), event.getDesc(), + event.getTenant(), event.getVnfWorkloadContext(), event.getEnvId()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribNotificationEventFactory(CommonAuditData commonFields, String currentState, String currentVersion, + String did, User modifier, String resourceName, + String resourceType, String topicName, OperationalEnvAuditData opEnvFields) { + + super(AuditingActionEnum.DISTRIBUTION_NOTIFY); + this.event = new DistributionNotificationEvent(getAction().getName(), commonFields, did, AuditBaseEventFactory.buildUserName(modifier), + currentState, currentVersion,resourceName, resourceType, topicName, opEnvFields); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java new file mode 100644 index 0000000000..3d71a200a3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditDistribStatusEventFactory extends AuditBaseEventFactory { + + private DistributionStatusEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" DID = \"%s\" CONSUMER_ID = \"%s\" " + + "TOPIC_NAME = \"%s\" RESOURCE_URL = \"%s\" STATUS_TIME = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), event.getResoureURL(), + event.getStatusTime(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditDistribStatusEventFactory(CommonAuditData commonFields, String did, String consumerId, String topicName, + String resourceURL, String statusTime) { + + super(AuditingActionEnum.DISTRIBUTION_STATUS); + this.event = new DistributionStatusEvent(getAction().getName(), commonFields, did, consumerId, topicName, resourceURL, statusTime); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java new file mode 100644 index 0000000000..79d524a0dc --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory { + + private AuditingGetUebClusterEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" STATUS = \"%s\" STATUS_DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditGetUebClusterEventFactory(CommonAuditData commonFields, String consumerId) { + + super(AuditingActionEnum.GET_UEB_CLUSTER); + this.event = new AuditingGetUebClusterEvent(getAction().getName(), commonFields, consumerId); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java new file mode 100644 index 0000000000..2dbcde7b2c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public abstract class AuditRegUnregDistribEngineEventFactory extends AuditDistribEngineEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" API_KEY = \"%s\" D_ENV = \"%s\" STATUS = \"%s\"" + + " DESC = \"%s\" DNOTIF_TOPIC = \"%s\" DSTATUS_TOPIC = \"%s\""; + + public AuditRegUnregDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, + String distStatusTopic, String distNotifTopic, String apiKey, String envName, String role) { + super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getApiKey(), event.getEnvironmentName(), + event.getStatus(), event.getDesc(), event.getDnotifTopic(),event.getDstatusTopic()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java new file mode 100644 index 0000000000..e2ce0312f7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditRegisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory { + + public AuditRegisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.DISTRIBUTION_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java new file mode 100644 index 0000000000..fe7f335c77 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditRemoveKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory { + + public AuditRemoveKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java new file mode 100644 index 0000000000..d402d38e25 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUnregisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory { + + public AuditUnregisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic, + String apiKey, String envName, String role) { + super(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java new file mode 100644 index 0000000000..942dae0507 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java @@ -0,0 +1,26 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditActivateServiceExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; + + public AuditActivateServiceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ACTIVATE_SERVICE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getStatus(), event.getServiceInstanceId(), + event.getInvariantUuid(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java new file mode 100644 index 0000000000..5e6256368e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" RESOURCE_NAME = \"%s\" " + + "RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditAssetExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(), + event.getResourceType(), event.getServiceInstanceId(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java new file mode 100644 index 0000000000..1a41d7d5f8 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditAssetGetMetadataExternalApiEventFactory extends AuditAssetExternalApiEventFactory { + + public AuditAssetGetMetadataExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_ASSET_METADATA, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..13558881c5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditAssetListExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(), + event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java new file mode 100644 index 0000000000..060cbd395e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalApiEventFactory { + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\"" + + " PREV_STATE = \"%s\" CURR_STATE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditChangeLifecycleExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(), + event.getCurrState(), event.getServiceInstanceId(), event.getInvariantUuid(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java new file mode 100644 index 0000000000..07bac13495 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\""; + + public AuditCreateResourceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(), + event.getCurrState(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getStatus(), + event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java new file mode 100644 index 0000000000..fd8be4cc47 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" + + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\"" + + " STATUS = \"%s\" DESC = \"%s\""; + + public AuditCrudExternalApiArtifactEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), + event.getResourceURL(), event.getModifier(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), + event.getArtifactData(), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..c2827b1e5d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditDeleteArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditDeleteArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_DELETE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java new file mode 100644 index 0000000000..134dfd2921 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalApiEventFactory { + + private static final String LOG_STR = "CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDownloadArtifactExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getConsumerId(), event.getResourceURL(),event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java new file mode 100644 index 0000000000..4e233dee27 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java @@ -0,0 +1,25 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditExternalApiEventFactory extends AuditBaseEventFactory { + + protected final ExternalApiEvent event; + + public AuditExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(action); + event = new ExternalApiEvent(getAction().getName(), commonFields, resourceType, resourceName, consumerId, resourceUrl, + prevParams, currParams, AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData) ; + } + + @Override + public AuditingGenericEvent getDbEvent() { return event; } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..e97614551f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory { + + public AuditGetAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_ASSET_LIST, commonFields, resourceType, resourceName, + consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java new file mode 100644 index 0000000000..379124dc4a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetFilteredAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory { + + public AuditGetFilteredAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_FILTERED_ASSET_LIST, commonFields, resourceType, resourceName, + consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java new file mode 100644 index 0000000000..168cd1b150 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditGetToscaModelExternalApiEventFactory extends AuditAssetExternalApiEventFactory { + + public AuditGetToscaModelExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.GET_TOSCA_MODEL, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..5af8ff3d0d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditUpdateArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditUpdateArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_UPDATE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java new file mode 100644 index 0000000000..02af363f46 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditUploadArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory { + + public AuditUploadArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName, + String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams, + String invariantUuid, User modifier, String artifactData) { + super(AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams, + invariantUuid, modifier, artifactData); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java new file mode 100644 index 0000000000..9bda0d22d6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + + public AuditArtifactResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + //TODO: check wheather or not "CONSUMER_ID =...RESOURCE_URL = " should be filled out - the info id not in the event + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getPrevArtifactUUID()), buildValue(event.getCurrArtifactUUID()), + buildValue(event.getArtifactData()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java new file mode 100644 index 0000000000..f5302957e1 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditCertificationResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " COMMENT = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getComment()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java new file mode 100644 index 0000000000..db76b78106 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditCreateUpdateResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" + + " STATUS = \"%s\" DESC = \"%s\""; + + + public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), event.getStatus(), event.getDesc()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java new file mode 100644 index 0000000000..62f95de6bd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" + + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditDistStateChangeRequestResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()), + buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()), + buildValue(event.getDid()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java new file mode 100644 index 0000000000..3fd41b9681 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.Constants; + +public class AuditDistStateChangeResourceAdminEventFactory extends AuditResourceAdminEventFactory { + + + private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" + + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" + + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" STATUS = \"%s\" DESC = \"%s\" COMMENT = \"%s\""; + + + public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did) { + super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, Constants.EMPTY_STRING); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()), + buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()), + buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getComment())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java new file mode 100644 index 0000000000..64da0fd6db --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResourceAdminEventFactory { + + + private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"" ; + + + public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, artifactData, comment, did, toscaNodeType); + } + + public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams, + String resourceType, String resourceName, + String invariantUuid, User modifier, String toscaNodeType) { + super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid, + modifier, null, null, null, toscaNodeType); + } + + @Override public String getLogMessage() { + return String.format(LOG_STR_TOSCA, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()), + buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()), + buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()), + buildValue(event.getCurrState()), buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getToscaNodeType())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java new file mode 100644 index 0000000000..2a188d2c1a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; + +public abstract class AuditResourceAdminEventFactory extends AuditBaseEventFactory { + + protected final ResourceAdminEvent event; + + public AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, + ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid, + User modifier, String artifactData, String comment, String did, String toscaNodeType) { + super(action); + + this.event = new ResourceAdminEvent(action.getName(), commonFields, prevParams, currParams, resourceType, + resourceName, invariantUuid, AuditBaseEventFactory.buildUserName(modifier), + artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java new file mode 100644 index 0000000000..c7ea8cc428 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditGetUsersListEventFactory extends AuditBaseEventFactory { + private final GetUsersListEvent event; + + private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier, + String userDetails) { + super(AuditingActionEnum.GET_USERS_LIST); + event = new GetUsersListEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier), userDetails); + } + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java new file mode 100644 index 0000000000..4f97ae12c9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUserAccessEventFactory extends AuditBaseEventFactory { + + protected final static String LOG_STR = "ACTION = \"%s\" USER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + private final UserAccessEvent event; + + + @Override + public String getLogMessage() { + return String.format(LOG_STR, event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc()); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + + public AuditUserAccessEventFactory(CommonAuditData commonFields, User user) { + super(AuditingActionEnum.USER_ACCESS); + event = new UserAccessEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(user)); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java new file mode 100644 index 0000000000..9c19c49b2d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java @@ -0,0 +1,33 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; + +public class AuditUserAdminEventFactory extends AuditBaseEventFactory { + + final private UserAdminEvent event; + + protected final static String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" USER_BEFORE = \"%s\" USER_AFTER = \"%s\" STATUS = \"%s\" DESC = \"%s\""; + + @Override + public String getLogMessage() { + return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getModifier()), buildValue(event.getUserBefore()), + buildValue(event.getUserAfter()), buildValue(event.getStatus()), buildValue(event.getDesc())); + } + + @Override + public AuditingGenericEvent getDbEvent() { + return event; + } + + public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, User userBefore, User userAfter) { + super(action); + event = new UserAdminEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier), + AuditBaseEventFactory.buildUserNameExtended(userBefore), + AuditBaseEventFactory.buildUserNameExtended(userAfter)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java deleted file mode 100644 index 824b70073e..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.clean; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.CleanComponentsConfiguration; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component("asdcComponentsCleaner") -public class AsdcComponentsCleanerTask implements Runnable { - - private static Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class.getName()); - - @javax.annotation.Resource - private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null; - - private List componentsToClean; - private long cleaningIntervalInMinutes; - - private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build()); - ScheduledFuture scheduledFuture = null; - - @PostConstruct - public void init() { - log.trace("Enter init method of AsdcComponentsCleaner"); - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration(); - - if (cleanComponentsConfiguration == null) { - log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration"); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, "AsdcComponentsCleanerTask.init()", "AsdcComponentsCleanerTask.init()"); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", "fecth configuration"); - return; - - } - componentsToClean = new ArrayList(); - List components = cleanComponentsConfiguration.getComponentsToClean(); - if (components == null) { - log.info("no component were configured for cleaning"); - } - for (String component : components) { - NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component); - if (typeEnum != null) - componentsToClean.add(typeEnum); - } - - long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes(); - - if (intervalInMinutes < 1) { - log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default"); - intervalInMinutes = 60; - } - cleaningIntervalInMinutes = intervalInMinutes; - - startTask(); - - log.trace("End init method of AsdcComponentsCleaner"); - } - - @PreDestroy - public void destroy() { - this.stopTask(); - shutdownExecutor(); - } - - public void startTask() { - - log.debug("start task for cleaning components"); - - try { - - if (scheduledService != null) { - log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes); - scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, TimeUnit.MINUTES); - - } - } catch (Exception e) { - log.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", e.getMessage()); - - } - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - log.debug("Stop cleaning task. result = {}", result); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, "try to stop the polling task"); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", "try to stop the polling task"); - } - scheduledFuture = null; - } - - } - - private void shutdownExecutor() { - if (scheduledService == null) - return; - - scheduledService.shutdown(); // Disable new tasks from being submitted - try { - // Wait a while for existing tasks to terminate - if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS)) { - scheduledService.shutdownNow(); // Cancel currently executing - // tasks - // Wait a while for tasks to respond to being cancelled - if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS)) - log.debug("Pool did not terminate"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - scheduledService.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } - - @Override - public void run() { - try { - componentsCleanBusinessLogic.cleanComponents(componentsToClean); - } catch (Exception e) { - log.error("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", e.getMessage()); - } - - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java deleted file mode 100644 index b12b55ba8b..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.clean; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; -import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; -import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import fj.data.Either; - -@Component("componentsCleanBusinessLogic") -public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { - - @Autowired - private ResourceBusinessLogic resourceBusinessLogic; - - @Autowired - private ServiceBusinessLogic serviceBusinessLogic; - - private static Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class.getName()); - - public Map, ResponseFormat>> cleanComponents(List componentsToClean) { - - Map, ResponseFormat>> cleanedComponents = new HashMap, ResponseFormat>>(); - - log.trace("start cleanComponents"); - for (NodeTypeEnum type : componentsToClean) { - switch (type) { - case Resource: - processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic); - break; - case Service: - processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic); - break; - default: - log.debug("{} component type does not have cleaning method defined", type); - break; - } - } - - log.trace("end cleanComponents"); - return cleanedComponents; - } - - private void processDeletionForType(Map, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) { - Either, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents(); - if (deleteMarkedResources.isRight()) { - log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage()); - } else { - if (log.isDebugEnabled()) { - StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": "); - for (String id : deleteMarkedResources.left().value()) { - sb.append(id).append(", "); - } - log.debug(sb.toString()); - } - } - cleanedComponents.put(type, deleteMarkedResources); - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java new file mode 100644 index 0000000000..0ee2dabf08 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java @@ -0,0 +1,1681 @@ +package org.openecomp.sdc.be.components.csar; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import fj.data.Either; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.CsarValidationUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.info.ArtifactTemplateInfo; +import org.openecomp.sdc.be.info.MergedArtifactInfo; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.heat.HeatParameterType; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.tosca.CsarUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH; + + +@org.springframework.stereotype.Component("csarArtifactsAndGroupsBusinessLogic") +public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(CsarArtifactsAndGroupsBusinessLogic.class); + private final Gson gson = new Gson(); + private static final Pattern pattern = Pattern.compile("\\..(.*?)\\.."); + @Autowired + protected ArtifactsBusinessLogic artifactsBusinessLogic; + + public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + String artifactsMetaFile, String artifactsMetaFileName, List createdArtifacts, + boolean shouldLock, boolean inTransaction) { + + log.debug("parseResourceArtifactsInfoFromFile start"); + return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()) + .left() + .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts,shouldLock, inTransaction)) + .right() + .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;}) + .left() + .bind( c -> getResourcetFromGraph(c)); + } + + + public Either updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + String artifactsMetaFile, String artifactsMetaFileName, List createdNewArtifacts, + boolean shouldLock, boolean inTransaction){ + + Resource updatedResource = resource; + + Either>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile( + updatedResource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); + if (parseResourceInfoFromYamlEither.isRight()) { + ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + List groups = updatedResource.getGroups(); + Map deplymentArtifact = updatedResource.getDeploymentArtifacts(); + if (deplymentArtifact == null || deplymentArtifact.isEmpty()) { + if(groups != null){ + List listToDelete = groups.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList()); + groupBusinessLogic.deleteGroups(updatedResource, listToDelete); + } + return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(), + createdNewArtifacts, shouldLock, inTransaction); + } + + List createdDeplymentArtifactsAfterDelete = deplymentArtifact.values().stream().collect(Collectors.toList()); + + int labelCounter = createdDeplymentArtifactsAfterDelete.size(); + + + ////////////////////////////////////// create set parsed + ////////////////////////////////////// artifacts/////////////////////////////////////////// + Map> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); + + + List artifactsWithoutGroups = null; + if (parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)) { + artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT); + parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); + } + Collection> parsedArifactsCollection = parsedArtifactsMap.values(); + + Either>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts, shouldLock, inTransaction, + createdDeplymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection); + if(parsedArtifactsPerGroupEither.isRight()){ + log.error("Failed to parse artifacts. Status is {} ", parsedArtifactsPerGroupEither.right().value()); + return Either.right(parsedArtifactsPerGroupEither.right().value()); + } + + Map> parsedGroup = parsedArtifactsPerGroupEither.left().value(); + + // find master in group + Map>> groupArtifact = findMasterArtifactInGroup( + groups, deplymentArtifact); + + ///////////////////////////////// find artifacts to + ///////////////////////////////// delete//////////////////////////////////////////////////// + + + Map> groupToDelete = new HashMap<>(); + Set artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeplymentArtifactsAfterDelete); + + Set jsonMasterArtifacts = parsedGroup.keySet(); + Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, + artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete); + + List deletedArtifacts = new ArrayList<>();; + Either deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow( + updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts); + if (deletedArtifactsEither.isRight()) { + log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value()); + + return Either.right(deletedArtifactsEither.right().value()); + + } + updatedResource = deletedArtifactsEither.left().value(); + + // need to update resource if we updated artifacts + if (!deletedArtifacts.isEmpty()) { + for (ArtifactDefinition deletedArtifact : deletedArtifacts) { + ArtifactDefinition artToRemove = null; + for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) { + if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) { + artToRemove = artFromResource; + break; + } + } + if (artToRemove != null) { + createdDeplymentArtifactsAfterDelete.remove(artToRemove); + } + + } + } + + ////////////// dissociate, associate or create + ////////////// artifacts//////////////////////////// + Either assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, + updatedResource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, + createdDeplymentArtifactsAfterDelete, mergedgroup, deletedArtifacts); + groups = updatedResource.getGroups(); + if (assDissotiateEither.isRight()) { + log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value()); + + return Either.right(assDissotiateEither.right().value()); + + } + updatedResource = assDissotiateEither.left().value(); + deplymentArtifact = updatedResource.getDeploymentArtifacts(); + createdDeplymentArtifactsAfterDelete.clear(); + if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { + for (Entry entry : deplymentArtifact.entrySet()) { + createdDeplymentArtifactsAfterDelete.add(entry.getValue()); + } + } + + // update vfModule names + Set groupForAssociateWithMembers = mergedgroup.keySet(); + if (groups != null && !groups.isEmpty()) { + Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNamesOnGraph(groups, updatedResource, inTransaction); + if (validateUpdateVfGroupNamesRes.isRight()) { + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + List heatGroups = null; + + heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + + for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) { + + if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) { + updatedGroupDef.getMembers().clear(); + } + Map members = new HashMap<>(); + Set artifactsGroup = new HashSet<>(); + artifactsGroup.addAll(updatedGroupDef.getArtifacts()); + associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, + artifactsGroup, members); + if (!members.isEmpty()) { + updatedGroupDef.setMembers(members); + + } + + } + + } + + //////////////// create new artifacts in update + //////////////// flow//////////////////////////// + List newArtifactsGroup = new ArrayList<>(); + + for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { + ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey(); + boolean isNewGroup = true; + for (Entry>> groupListEntry : groupArtifact + .entrySet()) { + Map> groupArtifacts = groupListEntry.getValue(); + Set group = groupArtifacts.keySet(); + for (ArtifactDefinition artifactInfo : group) { + if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) { + parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName()); + isNewGroup = false; + } + } + } + if (isNewGroup) { + newArtifactsGroup.add(parsedArtifactMaster); + } + + } + if (!newArtifactsGroup.isEmpty()) { + Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); + int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups); + Either validateGroupNamesRes = groupBusinessLogic + .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter); + if (validateGroupNamesRes.isRight()) { + return Either.right(validateGroupNamesRes.right().value()); + } + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, + newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, + shouldLock, inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + + // updatedGroup + if (!groupForAssociateWithMembers.isEmpty()) { + + List groupsId = groupForAssociateWithMembers.stream().map(e -> e) + .collect(Collectors.toList()); + + Either, ResponseFormat> updateVersionEither = groupBusinessLogic + .updateGroups(updatedResource, groupsId); + if (updateVersionEither.isRight()) { + log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); + + return Either.right(updateVersionEither.right().value()); + + } + } + if (artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()) { + for (ArtifactTemplateInfo t : artifactsWithoutGroups) { + List arrtifacts = new ArrayList(); + arrtifacts.add(t); + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, + arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + + } + + Either eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + return Either.left(eitherGerResource.left().value()); + } + + private Set findArtifactThatNotInGroupToDelete( + Map> parsedGroup, + List createdDeplymentArtifactsAfterDelete) { + Set artifactsToDelete = new HashSet<>(); + for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { + Set artifactsNames = parsedGroupSetEntry.getValue(); + for (ArtifactTemplateInfo template : artifactsNames) { + if(template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())){ + Optional op = createdDeplymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny(); + if(op.isPresent()){ + if(!op.get().getArtifactType().equalsIgnoreCase(template.getType())){ + artifactsToDelete.add(op.get()); + } + + } + } + } + } + + return artifactsToDelete; + } + + + private Either createResourceArtifacts(CsarInfo csarInfo, Resource resource, + Map> artifactsMap, + List createdArtifacts, boolean shouldLock, boolean inTransaction) { + + Either resStatus = Either.left(resource); + + Collection> arifactsCollection = artifactsMap.values(); + + for (List groupTemplateList : arifactsCollection) { + if (groupTemplateList != null) { + resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, + createdArtifacts, 0, shouldLock, inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + + return resStatus; + + } + + + private Either>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo, Resource resource, + List createdNewArtifacts, boolean shouldLock, boolean inTransaction, + List createdDeplymentArtifactsAfterDelete, int labelCounter, + Collection> parsedArifactsCollection) { + + Map> parsedGroup = new HashMap<>(); + + for (List parsedGroupTemplateList : parsedArifactsCollection) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + if (parsedGroupTemplate.getGroupName() != null) { + parsedGroupTemplate.setGroupName(""); + Set parsedArtifactsNames = new HashSet<>(); + parsedArtifactsNames.add(parsedGroupTemplate); + List relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { + createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames); + } + parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames); + } else { + List arrtifacts = new ArrayList<>(); + arrtifacts.add(parsedGroupTemplate); + Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, + resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, + labelCounter, shouldLock, inTransaction); + if (resStatus.isRight()) { + return Either.right(resStatus.right().value()); + } + + } + } + + } + return Either.left(parsedGroup); + } + + @SuppressWarnings({ "unchecked", "static-access" }) + public Either>, ResponseFormat> parseResourceArtifactsInfoFromFile( + Resource resource, String artifactsMetaFile, String artifactFileName, User user) { + + try { + JsonObject jsonElement = new JsonObject(); + jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass()); + + JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE); + if (importStructureElement == null || importStructureElement.isJsonNull()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + Map>> artifactTemplateMap = new HashMap<>(); + artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class); + if (artifactTemplateMap.isEmpty()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + Set artifactsTypeKeys = artifactTemplateMap.keySet(); + Map> artifactsMap = new HashMap<>(); + List allGroups = new ArrayList<>(); + for (String artifactsTypeKey : artifactsTypeKeys) { + + Either , ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName, + artifactTemplateMap, allGroups, artifactsTypeKey); + if(artifactTemplateInfoListEither.isRight()){ + return Either.right(artifactTemplateInfoListEither.right().value()); + } + artifactsMap.put(artifactsTypeKey, artifactTemplateInfoListEither.left().value()); + } + int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups()); + Either validateGroupNamesRes = groupBusinessLogic + .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter); + if (validateGroupNamesRes.isRight()) { + return Either.right(validateGroupNamesRes.right().value()); + } + return Either.left(artifactsMap); + } catch (Exception e) { + log.debug("Artifact file is not in expected format, fileName {}", artifactFileName); + log.debug("failed with exception.", e); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + } + + } + + private Either< List, ResponseFormat> parseArtifactTemplateList(String artifactFileName, + Map>> artifactTemplateMap, List allGroups, + String artifactsTypeKey) { + List> o = artifactTemplateMap.get(artifactsTypeKey); + Either, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule( + artifactsTypeKey, o); + if (artifactTemplateInfoListPairStatus.isRight()) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(artifactTemplateInfoListPairStatus.right().value()); + } + List artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value(); + if (artifactTemplateInfoList == null) { + log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected format, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); + + } + if (!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) { + allGroups.addAll(artifactTemplateInfoList); + } + return Either.left(artifactTemplateInfoList); + } + + private Either, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, + List> jsonObject) { + List artifactTemplateInfoList = new ArrayList<>(); + for (Map o : jsonObject) { + Either artifacttemplateInfoStatus = ArtifactTemplateInfo + .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, + null); + if (artifacttemplateInfoStatus.isRight()) { + return Either.right(artifacttemplateInfoStatus.right().value()); + } + + ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value(); + if (artifacttemplateInfo != null) { + artifactTemplateInfoList.add(artifacttemplateInfo); + } + + } + return Either.left(artifactTemplateInfoList); + } + + + + private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, List artifactsTemplateList, + List createdArtifacts, int labelCounter, boolean shouldLock, boolean inTransaction) { + Either resStatus = Either.left(resource); + List createdGroups = resource.getGroups(); + List heatGroups = null; + if (createdGroups != null && !createdGroups.isEmpty()) { + + heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + + } + List needToCreate = new ArrayList<>(); + for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { + String groupName = groupTemplateInfo.getGroupName(); + Set artifactsGroup = new HashSet<>(); + Set artifactsUUIDGroup = new HashSet<>(); + + log.debug("createDeploymentArtifactsFromCsar start"); + resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, + artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); + log.debug("createDeploymentArtifactsFromCsar end"); + if (resStatus.isRight()) { + return resStatus; + } + if (groupName != null && !groupName.isEmpty()) { + + Either groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo, + groupName, artifactsGroup, artifactsUUIDGroup); + if (groupDefinitionEither.isRight()) { + return Either.right(groupDefinitionEither.right().value()); + } + needToCreate.add(groupDefinitionEither.left().value()); + } + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + + componentParametersView.setIgnoreComponentInstances(false); + + Either component = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), componentParametersView); + + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + Either, ResponseFormat> createGroups = groupBusinessLogic + .addGroups(component.left().value(), needToCreate); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + + return Either.left(component.left().value()); + } + + private Either buildGroupDefinition(List createdArtifacts, + List heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName, + Set artifactsGroup, Set artifactsUUIDGroup) { + + Map members = new HashMap<>(); + + associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); + + List artifactsList = new ArrayList<>(artifactsGroup); + List artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup); + + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setName(groupName); + groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); + groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + + if (!members.isEmpty()) { + groupDefinition.setMembers(members); + } + List properties = new ArrayList<>(); + GroupProperty prop = new GroupProperty(); + prop.setName(Constants.IS_BASE); + prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); + properties.add(prop); + Either getLatestGroupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, + createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); + log.debug("createGroup start"); + return Either.left(groupDefinition); + } + + private Either createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, + Resource resource, Set artifactsGroup, Set artifactsUUIDGroup, + ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, int labelCounter, + boolean shoudLock, boolean inTransaction) { + Either resStatus = Either.left(resource); + + String artifactUid = ""; + String artifactEnvUid = ""; + String artifactUUID = ""; + + + // check if artifacts already exist + Either createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts); + if(createdArtifactEther.isRight()){ + return Either.right(createdArtifactEther.right().value()); + } + ArtifactDefinition createdArtifact = createdArtifactEther.left().value(); + if(createdArtifact == null){ + + Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, + artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction); + if (newArtifactEither.isRight()) { + resStatus = Either.right(newArtifactEither.right().value()); + return resStatus; + } + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } + }else{ + artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); + } + artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } + + List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null) { + for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { + resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, + artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + return resStatus; + } + + private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { + String artifactEnvUid = ""; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX; + } + return artifactEnvUid; + } + + private Either checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts){ + + ArtifactDefinition res = null; + String artifactFileName = artifactTemplateInfo.getFileName(); + Optional op = createdArtifacts.stream().filter(a -> a.getArtifactName().equals(artifactFileName)).findAny(); + if(op.isPresent()){ + res = op.get(); + if (!res.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), res.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), res.getArtifactType())); + } + } + return Either.left(res); + + + } + + private Either createDeploymentArtifact(CsarInfo csarInfo, Resource resource, + String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, + int label, boolean inTransaction) { + int updatedlabel = label; + final String artifactFileName = artifactTemplateInfo.getFileName(); + Either, ResponseFormat> artifactContententStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, + artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) { + return Either.right(artifactContententStatus.right().value()); + } + updatedlabel += createdArtifacts.size(); + + Map json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo, + artifactContententStatus.left().value().getValue(), updatedlabel); + + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), json, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE)); + + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + if (currentInfo.getHeatParameters() != null) { + + Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, + artifactTemplateInfo, currentInfo, false); + if (updateEnvEither.isRight()) { + log.debug("failed to update parameters to artifact {}", artifactFileName); + return Either.right(updateEnvEither.right().value()); + + } + currentInfo = updateEnvEither.left().value(); + + } + + createdArtifacts.add(currentInfo); + + return Either.left(currentInfo); + + } + + + + private Either updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, + ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { + + Resource updatedResource = resource; + Either resStatus = Either.left(currentInfo); + if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { + + Either, ResponseFormat> artifactparamsStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), + CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), + componentsUtils); + if (artifactparamsStatus.isRight()) { + resStatus = Either.right(artifactparamsStatus.right().value()); + return resStatus; + } + Either, ResponseFormat> propsStatus = extractHeatParameters( + ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), + artifactparamsStatus.left().value().getValue(), false); + + if (propsStatus.isLeft()) { + List updatedHeatEnvParams = propsStatus.left().value(); + resStatus = updateHeatParams(updatedResource, currentInfo, updatedHeatEnvParams); + if (resStatus.isRight()) { + return resStatus; + } + + } + } + if (isUpdateEnv) { + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreArtifacts(false); + parametersView.setIgnoreGroups(false); + + Either eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + resStatus = Either.right(responseFormat); + return resStatus; + + } + + updatedResource = eitherGerResource.left().value(); + Map artifacts = updatedResource.getDeploymentArtifacts(); + Optional op = artifacts.values().stream().filter( + p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())) + .findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + Either updateArifactOnResource = artifactToscaOperation + .updateArifactOnResource(artifactInfoHeatEnv, updatedResource.getUniqueId(), + artifactInfoHeatEnv.getUniqueId(), null, null); + if (updateArifactOnResource.isRight()) { + log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", + updatedResource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), + artifactInfoHeatEnv.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); + } + resStatus = Either.left(updateArifactOnResource.left().value()); + } + } + return resStatus; + } + + private Either, ResponseFormat> extractHeatParameters(String artifactType, + String fileName, byte[] content, boolean is64Encoded) { + // extract heat parameters + String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content); + Either, ResultStatusEnum> heatParameters = ImportUtils + .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType); + if (heatParameters.isRight()) { + log.debug("File {} is not in expected key-value form in csar ", fileName); + BeEcompErrorManager.getInstance().logInternalDataError( + "File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", + ErrorSeverity.ERROR); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName)); + + } + return Either.left(heatParameters.left().value()); + + } + + private Either updateHeatParams(Resource resource, + ArtifactDefinition currentInfo, List updatedHeatEnvParams) { + + Either resStatus = Either.left(currentInfo); + List currentHeatEnvParams = currentInfo.getListHeatParameters(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null + && !currentHeatEnvParams.isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) { + updatedParamValue = heatEnvParam.getDefaultValue(); + } + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, + ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); + resStatus = Either.right(responseFormat); + return resStatus; + } + currHeatParam.setCurrentValue( + paramType.getConverter().convert(updatedParamValue, null, null)); + + break; + } + } + } + currentInfo.setListHeatParameters(currentHeatEnvParams); + Either updateArifactOnResource = artifactToscaOperation + .updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), + null, null); + if (updateArifactOnResource.isRight()) { + log.debug( + "Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", + resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); + } + resStatus = Either.left(updateArifactOnResource.left().value()); + } + return resStatus; + } + + + + + public Either, ResponseFormat> createOrUpdateCsarArtifactFromJson( + Resource resource, User user, Map json, ArtifactOperationInfo operation) { + + String jsonStr = gson.toJson(json); + + String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr); + ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, + ArtifactDefinition.class); + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic + .validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, + artifactUniqueId, artifactDefinitionFromJson, origMd5, jsonStr, null, null, user, + resource, false, true, false); + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + return Either.left(uploadArtifactToService.left().value()); + } + + private void associateMembersToArtifacts(List createdArtifacts, + List artifactsFromResource, List heatGroups, + Set artifactsGroup, Map members) { + if (heatGroups != null && !heatGroups.isEmpty()) { + for (GroupDefinition heatGroup : heatGroups) { + List grpoupProps = heatGroup.convertToGroupProperties(); + if (grpoupProps != null) { + associatemembersToVFgroups(createdArtifacts, artifactsFromResource, grpoupProps, artifactsGroup, heatGroup, members); + } + } + + } + } + + private void associatemembersToVFgroups(List createdArtifacts,List artifactsFromResource, List grpoupProps, Set artifactsGroup, GroupDefinition heatGroup, Map members){ + Optional op = grpoupProps.stream() + .filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny(); + if (op.isPresent()) { + GroupProperty prop = op.get(); + String heatFileNAme = prop.getValue(); + if (null == heatFileNAme || heatFileNAme.isEmpty()) { + return; + } + List artifacts = new ArrayList<>(); + for (String artifactId : artifactsGroup) { + Optional opArt = createdArtifacts.stream() + .filter(p -> p.getUniqueId().equals(artifactId)).findAny(); + if (opArt.isPresent()) { + artifacts.add(opArt.get()); + } + if (artifactsFromResource != null) { + opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)) + .findAny(); + if (opArt.isPresent()) { + artifacts.add(opArt.get()); + } + } + } + Optional resOp = artifacts.stream() + .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); + if (resOp.isPresent()) { + members.putAll(heatGroup.getMembers()); + } + } + } + + public List createVfModuleAdditionalProperties(boolean isBase, String moduleName, + List properties, List deploymentArtifacts, List artifactsInGroup, + GroupTypeDefinition groupType) { + Map vfModuleProperties = ConfigurationManager.getConfigurationManager() + .getConfiguration().getVfModuleProperties(); + vfModuleProperties.entrySet().forEach(p -> { + GroupProperty prop = new GroupProperty(); + prop.setName(p.getKey()); + if (isBase) { + prop.setValue(p.getValue().getForBaseModule()); + prop.setDefaultValue(p.getValue().getForBaseModule()); + } else { + prop.setValue(p.getValue().getForNonBaseModule()); + prop.setDefaultValue(p.getValue().getForNonBaseModule()); + } + properties.add(prop); + + }); + GroupProperty proplabel = new GroupProperty(); + proplabel.setName("vf_module_label"); + + Matcher matcher = pattern.matcher(moduleName); + + if (matcher.find()) { + proplabel.setValue(matcher.group(1)); + proplabel.setDefaultValue(matcher.group(1)); + } else { + proplabel.setValue(moduleName); + proplabel.setDefaultValue(moduleName); + } + properties.add(proplabel); + + GroupProperty propvolume = new GroupProperty(); + propvolume.setName("volume_group"); + boolean isVolume = false; + for (String artifactId : artifactsInGroup) { + ArtifactDefinition artifactDef = null; + artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId); + if (artifactDef != null + && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + isVolume = true; + break; + } + } + propvolume.setValue(String.valueOf(isVolume)); + propvolume.setDefaultValue(String.valueOf(isVolume)); + properties.add(propvolume); + mergeWithGroupTypeProperties(properties, groupType.getProperties()); + return properties; + } + + private void mergeWithGroupTypeProperties(List properties, + List groupTypeProperties) { + + Map propertiesMap = properties.stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p)); + for (PropertyDefinition groupTypeProperty : groupTypeProperties) { + if (!propertiesMap.containsKey(groupTypeProperty.getName())) { + properties.add(new GroupProperty(groupTypeProperty)); + } + } + } + + private Map mergeGroupInUpdateFlow( + Map>> groupArtifact, + Map> parsedGroup, Set artifactsToDelete, + Map> groupToDelete, Set jsonMasterArtifacts, + List createdDeplymentArtifacts) { + Map mergedgroup = new HashMap<>(); + for (Entry>> groupListEntry : groupArtifact + .entrySet()) { + Map> createdArtifactMap = groupListEntry.getValue(); + boolean isNeedToDeleteGroup = true; + List listToDelete = null; + for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { + listToDelete = createdArtifactMap.get(maserArtifact); + for (ArtifactDefinition artToDelete : listToDelete) { + findArtifactToDelete(parsedGroup, artifactsToDelete, artToDelete, createdDeplymentArtifacts); + } + if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) { + GroupDefinition group = groupListEntry.getKey(); + for (ArtifactDefinition artifactDefinition : artifactsToDelete) { + if (CollectionUtils.isNotEmpty(group.getArtifacts()) + && group.getArtifacts().contains(artifactDefinition.getUniqueId())) { + group.getArtifacts().remove(artifactDefinition.getUniqueId()); + + } + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) + && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) { + group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID()); + + } + } + + } + + for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { + if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) { + MergedArtifactInfo mergedGroup = new MergedArtifactInfo(); + mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact); + mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact)); + mergedgroup.put(groupListEntry.getKey(), mergedGroup); + isNeedToDeleteGroup = false; + + } + } + + } + if (isNeedToDeleteGroup) { + groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete); + } + + } + return mergedgroup; + } + + private void findArtifactToDelete(Map> parsedGroup, + Set artifactsToDelete, ArtifactDefinition artifact, + List createdDeplymentArtifacts) { + boolean isNeedToDeleteArtifact = true; + String artifactType = artifact.getArtifactType(); + ArtifactDefinition generatedFromArt = null; + if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { + Optional op = createdDeplymentArtifacts.stream() + .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + generatedFromArt = op.get(); + } + + } + + for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { + Set artifactsNames = parsedGroupSetEntry.getValue(); + for (ArtifactTemplateInfo template : artifactsNames) { + if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) + && artifactType.equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; + + } else { + + if (generatedFromArt != null) { + if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) + && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { + isNeedToDeleteArtifact = false; + break; + } + } + } + } + + } + if (isNeedToDeleteArtifact) { + artifactsToDelete.add(artifact); + + } + } + + private Map>> findMasterArtifactInGroup( + List groups, Map deplymentArtifact) { + Map>> groupArtifact = new HashMap<>(); + + for (GroupDefinition group : groups) { + Map> gupsMap = new HashMap<>(); + List artifacts = new ArrayList<>(); + List artifactsList = group.getArtifacts(); + if (artifactsList != null && !artifactsList.isEmpty()) { + + ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, + artifactsList); + if (masterArtifact != null) { + gupsMap.put(masterArtifact, artifacts); + } + groupArtifact.put(group, gupsMap); + + } + } + return groupArtifact; + } + + private Either deleteArtifactsInUpdateCsarFlow(Resource resource, + User user, boolean shouldLock, boolean inTransaction, Set artifactsToDelete, + Map> groupToDelete, List deletedArtifacts) { + + Resource updatedResource = resource; + + String resourceId = updatedResource.getUniqueId(); + if (!artifactsToDelete.isEmpty()) { + for (ArtifactDefinition artifact : artifactsToDelete) { + String artifactType = artifact.getArtifactType(); + ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); + if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { + Either, ResponseFormat> handleDelete = artifactsBusinessLogic + .handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, + ComponentTypeEnum.RESOURCE, updatedResource, shouldLock, inTransaction); + if (handleDelete.isRight()) { + return Either.right(handleDelete.right().value()); + } + + deletedArtifacts.add(handleDelete.left().value().left().value()); + } + + } + } + if (!groupToDelete.isEmpty()) { + log.debug("try to delete group"); + List groupDefinitionstoDelete = new ArrayList<>(); + List groups = updatedResource.getGroups(); + for (Entry> deleteGroup : groupToDelete.entrySet()) { + Optional op = groups.stream() + .filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny(); + if (op.isPresent()) { + groupDefinitionstoDelete.add(op.get()); + } + + } + if (!groupDefinitionstoDelete.isEmpty()) { + Either, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, groupDefinitionstoDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + } + List oldGroups = updatedResource.getGroups(); + Either eitherGerResource = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + updatedResource = eitherGerResource.left().value(); + updatedResource.setGroups(oldGroups); + return Either.left(updatedResource); + } + + private void createArtifactsGroupSet(List parsedGroupTemplateList, + Set parsedArtifactsName) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + parsedArtifactsName.add(parsedGroupTemplate); + List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); + } + } + } + + private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, List artifactsTemplateList, + List createdNewArtifacts, List artifactsFromResource, + int labelCounter, boolean shouldLock, boolean inTransaction) { + + Resource updatedResource = resource; + + Either resStatus = Either.left(updatedResource); + List createdGroups = updatedResource.getGroups(); + List heatGroups = null; + if (createdGroups != null && !createdGroups.isEmpty()) { + heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); + } + + List needToAdd = new ArrayList<>(); + for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { + String groupName = groupTemplateInfo.getGroupName(); + Set artifactsGroup = new HashSet<>(); + Set artifactsUUIDGroup = new HashSet<>(); + + resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup, + groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + if (groupName != null && !groupName.isEmpty()) { + Map members = new HashMap<>(); + associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, + members); + + List artifactsList = new ArrayList<>(artifactsGroup); + List artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup); + + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setName(groupName); + groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); + groupDefinition.setArtifacts(artifactsList); + groupDefinition.setArtifactsUuid(artifactsUUIDList); + + if (!members.isEmpty()) { + groupDefinition.setMembers(members); + } + + List properties = new ArrayList<>(); + GroupProperty prop = new GroupProperty(); + prop.setName(Constants.IS_BASE); + prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); + properties.add(prop); + + List createdArtifacts = new ArrayList<>(); + createdArtifacts.addAll(createdNewArtifacts); + createdArtifacts.addAll(artifactsFromResource); + Either getLatestGroupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); + if (getLatestGroupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); + } + properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, + createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); + groupDefinition.convertFromGroupProperties(properties); + + needToAdd.add(groupDefinition); + } + } + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreComponentInstances(false); + + Either component = toscaOperationFacade + .getToscaElement(updatedResource.getUniqueId(), componentParametersView); + if (component.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + updatedResource = component.left().value(); + + Either, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd); + if (addGroups.isRight()) { + return Either.right(addGroups.right().value()); + } + + return resStatus; + } + + private Either createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, + Set artifactsGroup, Set artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo, + List createdArtifacts, List artifactsFromResource, int labelCounter, + boolean shoudLock, boolean inTransaction) { + Either resStatus = Either.left(resource); + String artifactFileName = artifactTemplateInfo.getFileName(); + String artifactUid = ""; + String artifactUUID = ""; + String artifactEnvUid = ""; + boolean alreadyExist = false; + + // check if artifacts already exist + if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) { + for (ArtifactDefinition artifactFromResource : artifactsFromResource) { + if (artifactFromResource.getArtifactName().equals(artifactFileName)) { + artifactUid = artifactFromResource.getUniqueId(); + artifactUUID = artifactFromResource.getArtifactUUID(); + if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), artifactFromResource.getArtifactType())); + } + alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource); + break; + } + + } + + } + if (!alreadyExist) { + for (ArtifactDefinition createdArtifact : createdArtifacts) { + if (createdArtifact.getArtifactName().equals(artifactFileName)) { + artifactUid = createdArtifact.getUniqueId(); + artifactUUID = createdArtifact.getArtifactUUID(); + + if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, + artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); + } + alreadyExist = true; + artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); + break; + } + + } + } + // if not exist need to create + if (!alreadyExist) { + + Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, + ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction); + if (newArtifactEither.isRight()) { + resStatus = Either.right(newArtifactEither.right().value()); + return resStatus; + } + ArtifactDefinition newArtifact = newArtifactEither.left().value(); + artifactUid = newArtifact.getUniqueId(); + artifactUUID = newArtifact.getArtifactUUID(); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); + } + } + + artifactsGroup.add(artifactUid); + artifactsUUIDGroup.add(artifactUUID); + if (!artifactEnvUid.isEmpty()) { + artifactsGroup.add(artifactEnvUid); + } + + List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null) { + for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { + resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, + relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, + inTransaction); + if (resStatus.isRight()) { + return resStatus; + } + } + } + return resStatus; + } + + private Either associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, + Resource resource, List createdNewArtifacts, int labelCounter, boolean shouldLock, + boolean inTransaction, List createdDeplymentArtifactsAfterDelete, + Map mergedgroup, List deletedArtifacts) { + Map> artifactsToAssotiate = new HashMap<>(); + Map>> artifactsToUpdateMap = new HashMap<>(); + Either resEither = Either.left(resource); + for (Entry entry : mergedgroup.entrySet()) { + List dissArtifactsInGroup = entry.getValue() + .getListToDissotiateArtifactFromGroup(deletedArtifacts); + GroupDefinition grDef = entry.getKey(); + if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) { + for (ArtifactDefinition art : dissArtifactsInGroup) { + grDef.getArtifacts().remove(art.getUniqueId()); + grDef.getArtifactsUuid().remove(art.getArtifactUUID()); + } + } + + List newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup(); + if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) { + artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup); + } + + List> artifactsToUpdate = entry.getValue() + .getListToUpdateArtifactInGroup(); + if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) { + artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate); + } + } + + if (!artifactsToUpdateMap.isEmpty()) { + List updatedArtifacts = new ArrayList<>(); + for (Entry>> artifactsToUpdateEntry : artifactsToUpdateMap + .entrySet()) { + List> artifactsToUpdateList = artifactsToUpdateEntry + .getValue(); + GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey(); + + for (ImmutablePair artifact : artifactsToUpdateList) { + String prevUUID = artifact.getKey().getArtifactUUID(); + String prevId = artifact.getKey().getUniqueId(); + String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey()); + Either updateArtifactEither = updateDeploymentArtifactsFromCsar( + csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts, + artifact.getRight().getRelatedArtifactsInfo()); + if (updateArtifactEither.isRight()) { + log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value()); + resEither = Either.right(updateArtifactEither.right().value()); + return resEither; + } + ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value(); + if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) + || !prevId.equals(artAfterUpdate.getUniqueId())) { + groupToUpdate.getArtifacts().remove(prevId); + groupToUpdate.getArtifactsUuid().remove(prevUUID); + groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId()); + groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); + } + Optional op = updatedArtifacts.stream() + .filter(p -> p.getGeneratedFromId() != null + && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())) + .findAny(); + if (op.isPresent()) { + ArtifactDefinition artifactInfoHeatEnv = op.get(); + groupToUpdate.getArtifacts().remove(prevHeatEnvId); + groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId()); + } + + } + } + } + + for (Entry> associateEntry : artifactsToAssotiate.entrySet()) { + List associatedArtifact = associateEntry.getValue(); + Set arifactsUids = new HashSet<>(); + Set arifactsUuids = new HashSet<>(); + for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try + // to + // find + // artifact + // in + // resource + boolean isCreate = true; + for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) { + if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) { + arifactsUids.add(createdArtifact.getUniqueId()); + arifactsUuids.add(createdArtifact.getArtifactUUID()); + isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + Optional op = createdDeplymentArtifactsAfterDelete.stream() + .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); + if (op.isPresent()) { + this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), + resource.getComponentType().getNodeType()); + + } + } + + break; + } + + } + if (isCreate) { // check if already created + for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) { + if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) { + arifactsUids.add(createdNewArtifact.getUniqueId()); + arifactsUuids.add(createdNewArtifact.getArtifactUUID()); + isCreate = false; + String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact); + if (!heatEnvId.isEmpty()) { + arifactsUids.add(heatEnvId); + } + break; + } + } + } + + if (isCreate) { + Either createArtifactEither = createDeploymentArtifact(csarInfo, + resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, inTransaction); + if (createArtifactEither.isRight()) { + resEither = Either.right(createArtifactEither.right().value()); + return resEither; + } + ArtifactDefinition createdArtifact = createArtifactEither.left().value(); + arifactsUids.add(createdArtifact.getUniqueId()); + arifactsUuids.add(createdArtifact.getArtifactUUID()); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); + if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET + || artifactType == ArtifactTypeEnum.HEAT_VOL) { + Either createHeatEnvPlaceHolder = artifactsBusinessLogic + .createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, + resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), + csarInfo.getModifier(), resource, null); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId(); + arifactsUids.add(heatEnvId); + } + } + + } + if (arifactsUids != null && !arifactsUids.isEmpty()) { + List artifactsToAssociate = new ArrayList<>(); + artifactsToAssociate.addAll(arifactsUids); + GroupDefinition assotiateGroup = associateEntry.getKey(); + assotiateGroup.getArtifacts().addAll(arifactsUids); + assotiateGroup.getArtifactsUuid().addAll(arifactsUuids); + } + } + + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreArtifacts(false); + parametersView.setIgnoreGroups(false); + + Either eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + resEither = Either.right(responseFormat); + return resEither; + + } + resEither = Either.left(eitherGerResource.left().value()); + return resEither; + } + + private Either updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, + Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo, + List updatedArtifacts, List updatedRequiredArtifacts) { + + Either resStatus = null; + String artifactFileName = artifactTemplateInfo.getFileName(); + + // check if artifacts already exist + for (ArtifactDefinition updatedArtifact : updatedArtifacts) { + if (updatedArtifact.getArtifactName().equals(artifactFileName)) { + if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { + log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, + artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()); + BeEcompErrorManager.getInstance().logInternalDataError( + "Artifact file is not in expected formatr, fileName " + artifactFileName, + "Artifact internals are invalid", ErrorSeverity.ERROR); + resStatus = Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, + artifactTemplateInfo.getType(), updatedArtifact.getArtifactType())); + return resStatus; + } + resStatus = Either.left(updatedArtifact); + return resStatus; + } + + } + + Either, ResponseFormat> artifactContententStatus = CsarValidationUtils + .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), + CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); + if (artifactContententStatus.isRight()) { + resStatus = Either.right(artifactContententStatus.right().value()); + return resStatus; + } + + Map json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, + oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), + oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(), + artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts, oldArtifact.getIsFromCsar()); + + Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), json, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE)); + + if (uploadArtifactToService.isRight()) { + resStatus = Either.right(uploadArtifactToService.right().value()); + return resStatus; + } + ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); + updatedArtifacts.add(currentInfo); + + Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, + artifactTemplateInfo, currentInfo, true); + if (updateEnvEither.isRight()) { + log.debug("failed to update parameters to artifact {}", artifactFileName); + resStatus = Either.right(updateEnvEither.right().value()); + return resStatus; + } + + updatedArtifacts.add(updateEnvEither.left().value()); + resStatus = Either.left(currentInfo); + + return resStatus; + + } + + public Either deleteVFModules(Resource resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) { + Resource updatedResource = resource; + List groupsToDelete = updatedResource.getGroups(); + if(groupsToDelete != null && !groupsToDelete.isEmpty()){ + List vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList()); + if(vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()){ + for(GroupDefinition gr : vfGroupsToDelete){ + List artifacts = gr.getArtifacts(); + for (String artifactId : artifacts) { + Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, + updatedResource, shouldLock, inTransaction); + if (handleDelete.isRight()) { + log.debug("Couldn't delete artifact {}", artifactId); + return Either.right(handleDelete.right().value()); + } + } + + } + groupBusinessLogic.deleteGroups(updatedResource, vfGroupsToDelete); + + Either eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId()); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource); + + return Either.right(responseFormat); + + } + updatedResource = eitherGetResource.left().value(); + } + } + return Either.left(updatedResource); + } + + private Either getResourcetFromGraph(Resource component){ + log.debug("getResource start"); + return toscaOperationFacade.getToscaElement(component.getUniqueId()) + .right() + .map(rf -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(rf), component)) + .left() + .map (c -> (Resource) c); + + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java new file mode 100644 index 0000000000..0519f435e3 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.http.conn.ConnectTimeoutException; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; +import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.SupplierThrows; +import org.openecomp.sdc.common.http.client.api.HttpExecuteException; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.client.api.Responses; +import org.openecomp.sdc.common.http.config.ExternalServiceConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.util.Properties; +import java.util.UUID; + +@Component +public class AaiRequestHandler { + + private static final Logger logger = LoggerFactory.getLogger(AaiRequestHandler.class); + private ExternalServiceConfig aaiConfig; + + protected static final String OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM = "operationalEnvironments"; + protected static final String OPERATIONAL_ENV_RESOURCE = "/operational-environment"; + + @PostConstruct + public void init() { + logger.debug("AaiRequestHandler has been initialized."); + + aaiConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getAaiConfig(); + logger.debug("AaiRequestHandler Configuration={}", aaiConfig); + } + + + public HttpResponse getOperationalEnvById(String id) { + Properties headers = createHeaders(); + String url = String.format("%s%s%s/%s", + aaiConfig.getHttpRequestConfig().getServerRootUrl(), + aaiConfig.getHttpRequestConfig().getResourceNamespaces().get(OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM), + OPERATIONAL_ENV_RESOURCE, id); + + SupplierThrows, Exception> httpGet = () -> HttpRequest.get(url, headers, aaiConfig.getHttpClientConfig()); + long maxRetries = aaiConfig.getHttpClientConfig().getNumOfRetries(); + try { + return FunctionalInterfaces.retryMethodOnException(httpGet, this::retryOnException, maxRetries); + } + catch (Exception e) { + logger.debug("Request failed with exception {}", getCause(e).getMessage()); + return Responses.INTERNAL_SERVER_ERROR; + } + } + + + private boolean retryOnException(Exception e) { + Throwable cause = getCause(e); + return !(cause instanceof ConnectTimeoutException || cause instanceof ConnectException || cause instanceof SocketTimeoutException); + } + + + private Throwable getCause(Exception e) { + if (e instanceof HttpExecuteException) { + return e.getCause(); + } + return e; + } + + + private Properties createHeaders() { + Properties headers = new Properties(); + headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.put(Constants.X_TRANSACTION_ID_HEADER, UUID.randomUUID().toString()); + + return headers; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java index e1a1270fe3..9c46c68cd8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java @@ -20,177 +20,185 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; - public class ArtifactInfoImpl implements IArtifactInfo { - private String artifactName; - private ArtifactTypeEnum artifactType; - private String artifactURL; - private String artifactChecksum; - private String artifactDescription; - private Integer artifactTimeout; - private String artifactUUID; - private String artifactVersion; - private String generatedFromUUID; - private List relatedArtifacts; - - public ArtifactInfoImpl() { - } - - private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List relatedArtifacts) { - artifactName = artifactDef.getArtifactName(); - artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType()); - artifactChecksum = artifactDef.getArtifactChecksum(); - artifactDescription = artifactDef.getDescription(); - artifactTimeout = artifactDef.getTimeout(); - artifactUUID = artifactDef.getArtifactUUID(); - artifactVersion = artifactDef.getArtifactVersion(); - this.relatedArtifacts = relatedArtifacts; - this.generatedFromUUID = generatedFromUUID; - } - - public static List convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection list) { - List ret = new ArrayList(); - Map> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); - if (list != null) { - for (ArtifactDefinition artifactDef : list) { - String generatedFromUUID = null; - if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { - ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); - generatedFromUUID = artifactFrom.getArtifactUUID(); - } - ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts())); - String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName()); - artifactInfoImpl.setArtifactURL(artifactURL); - ret.add(artifactInfoImpl); - } - } - return ret; - - } - - public static List convertServiceArtifactToArtifactInfoImpl(Service service, Collection list) { - List ret = new ArrayList(); - Map> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); - if (list != null) { - for (ArtifactDefinition artifactDef : list) { - String generatedFromUUID = null; - if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { - ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); - generatedFromUUID = artifactFrom.getArtifactUUID(); - } - ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts())); - String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName()); - artifactInfoImpl.setArtifactURL(artifactURL); - ret.add(artifactInfoImpl); - } - } - return ret; - - } - - private static List getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map artifacts) { - List requiredArtifacts = null; - if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) { - requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList()); - } - return requiredArtifacts; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public void setArtifactType(ArtifactTypeEnum artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public void setArtifactChecksum(String artifactChecksum) { - this.artifactChecksum = artifactChecksum; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public Integer getArtifactTimeout() { - return artifactTimeout; - } - - public void setArtifactTimeout(Integer artifactTimeout) { - this.artifactTimeout = artifactTimeout; - } - - public List getRelatedArtifacts() { - return relatedArtifacts; - } - - public void setRelatedArtifacts(List relatedArtifacts) { - this.relatedArtifacts = relatedArtifacts; - } - - @Override - public String toString() { - return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" - + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]"; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getGeneratedFromUUID() { - return generatedFromUUID; - } - - public void setGeneratedFromUUID(String generatedFromUUID) { - this.generatedFromUUID = generatedFromUUID; - } + private String artifactName; + private ArtifactTypeEnum artifactType; + private String artifactURL; + private String artifactChecksum; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactUUID; + private String artifactVersion; + private String generatedFromUUID; + private List relatedArtifacts; + + public ArtifactInfoImpl() { + } + + private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List relatedArtifacts) { + artifactName = artifactDef.getArtifactName(); + artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType()); + artifactChecksum = artifactDef.getArtifactChecksum(); + artifactDescription = artifactDef.getDescription(); + artifactTimeout = artifactDef.getTimeout(); + artifactUUID = artifactDef.getArtifactUUID(); + artifactVersion = artifactDef.getArtifactVersion(); + this.relatedArtifacts = relatedArtifacts; + this.generatedFromUUID = generatedFromUUID; + } + + public static List convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection list) { + List ret = new ArrayList(); + Map> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); + if (list != null) { + for (ArtifactDefinition artifactDef : list) { + String generatedFromUUID = null; + if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { + ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); + generatedFromUUID = artifactFrom.getArtifactUUID(); + } + ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts())); + String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName()); + artifactInfoImpl.setArtifactURL(artifactURL); + ret.add(artifactInfoImpl); + } + } + ret.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout); + return ret; + + } + + public static List convertServiceArtifactToArtifactInfoImpl(Service service, Collection list) { + List ret = new ArrayList(); + Map> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId)); + if (list != null) { + for (ArtifactDefinition artifactDef : list) { + String generatedFromUUID = null; + if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) { + ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0); + generatedFromUUID = artifactFrom.getArtifactUUID(); + } + ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts())); + String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName()); + artifactInfoImpl.setArtifactURL(artifactURL); + ret.add(artifactInfoImpl); + } + } + return ret; + + } + + private static List getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map artifacts) { + List requiredArtifacts = null; + if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) { + requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList()); + } + return requiredArtifacts; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public void setArtifactType(ArtifactTypeEnum artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public List getRelatedArtifacts() { + return relatedArtifacts; + } + + public void setRelatedArtifacts(List relatedArtifacts) { + this.relatedArtifacts = relatedArtifacts; + } + + @Override + public String toString() { + return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]"; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + public void updateArtifactTimeout(){ + int currentConfigTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getCurrentArtifactInstallationTimeout(); + if(artifactTimeout == null || artifactTimeout < currentConfigTimeout) + artifactTimeout = currentConfigTimeout; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java index 149ea2286a..3251f3d047 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java @@ -20,67 +20,67 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; + import java.util.ArrayList; import java.util.List; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; - public class CambriaErrorResponse { - public static final int HTTP_OK = 200; + public static final int HTTP_OK = 200; - public static final int HTTP_INTERNAL_SERVER_ERROR = 500; + public static final int HTTP_INTERNAL_SERVER_ERROR = 500; - CambriaOperationStatus operationStatus; - Integer httpCode; - List variables = new ArrayList(); + CambriaOperationStatus operationStatus; + Integer httpCode; + List variables = new ArrayList(); - public CambriaErrorResponse() { - super(); - } + public CambriaErrorResponse() { + super(); + } - public CambriaErrorResponse(CambriaOperationStatus operationStatus) { - super(); - this.operationStatus = operationStatus; - } + public CambriaErrorResponse(CambriaOperationStatus operationStatus) { + super(); + this.operationStatus = operationStatus; + } - public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) { - super(); - this.operationStatus = operationStatus; - this.httpCode = httpCode; - } + public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) { + super(); + this.operationStatus = operationStatus; + this.httpCode = httpCode; + } - public CambriaOperationStatus getOperationStatus() { - return operationStatus; - } + public CambriaOperationStatus getOperationStatus() { + return operationStatus; + } - public void setOperationStatus(CambriaOperationStatus operationStatus) { - this.operationStatus = operationStatus; - } + public void setOperationStatus(CambriaOperationStatus operationStatus) { + this.operationStatus = operationStatus; + } - public Integer getHttpCode() { - return httpCode; - } + public Integer getHttpCode() { + return httpCode; + } - public void setHttpCode(Integer httpCode) { - this.httpCode = httpCode; - } + public void setHttpCode(Integer httpCode) { + this.httpCode = httpCode; + } - public void addVariable(String variable) { - variables.add(variable); - } + public void addVariable(String variable) { + variables.add(variable); + } - public List getVariables() { - return variables; - } + public List getVariables() { + return variables; + } - public void setVariables(List variables) { - this.variables = variables; - } + public void setVariables(List variables) { + this.variables = variables; + } - @Override - public String toString() { - return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]"; - } + @Override + public String toString() { + return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java index c496715a02..d6fee9a9d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java @@ -20,25 +20,7 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.apiClient.http.HttpException; import com.att.nsa.apiClient.http.HttpObjectNotFoundException; import com.att.nsa.cambria.client.CambriaBatchingPublisher; @@ -53,574 +35,591 @@ import com.att.nsa.cambria.client.CambriaConsumer; import com.att.nsa.cambria.client.CambriaIdentityManager; import com.att.nsa.cambria.client.CambriaPublisher.message; import com.att.nsa.cambria.client.CambriaTopicManager; +import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; - import fj.data.Either; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Component("cambriaHandler") public class CambriaHandler { - private static Logger logger = LoggerFactory.getLogger(CambriaHandler.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(CambriaHandler.class); + + private static final String PARTITION_KEY = "asdc" + "aa"; + + private final String SEND_NOTIFICATION = "send notification"; + + private Gson gson = new Gson(); + + private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionStatusTopic().getConsumerId(); + + + + /** + * process the response error from Cambria client + * + * @param message + * @return + */ + private Integer processMessageException(String message) { + + String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" }; + + Integer result = checkPattern(patterns[0], message, 2); + if (result != null) { + return result; + } + result = checkPattern(patterns[1], message, 2); + + return result; + + } + + /** + * check whether the message has a match with a given pattern inside it + * + * @param patternStr + * @param message + * @param groupIndex + * @return + */ + private Integer checkPattern(String patternStr, String message, int groupIndex) { + Integer result = null; + + Pattern pattern = Pattern.compile(patternStr); + Matcher matcher = pattern.matcher(message); + boolean find = matcher.find(); + if (find) { + String httpCode = matcher.group(groupIndex); + if (httpCode != null) { + try { + result = Integer.valueOf(httpCode); + } catch (NumberFormatException e) { + logger.debug("Failed to parse http code {}", httpCode); + } + } + } + return result; + } + + /** + * retrieve all topics from U-EB server + * + * @param hostSet + * @return + */ + public Either, CambriaErrorResponse> getTopics(List hostSet) { + + CambriaTopicManager createTopicManager = null; + try { + + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet)); + + Set topics = createTopicManager.getTopics(); + + if (topics == null || true == topics.isEmpty()) { + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null); + return Either.right(cambriaErrorResponse); + } + + return Either.left(topics); + + } catch (IOException | GeneralSecurityException e) { + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + logger.debug("Failed to fetch topics from U-EB server", e); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics"); + + return Either.right(cambriaErrorResponse); + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + } + + /** + * process the error message from Cambria client. + * + * set Cambria status and http code in case we succeed to fetch it + * + * @return + */ + private CambriaErrorResponse processError(Exception e) { + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(); + + Integer httpCode = processMessageException(e.getMessage()); + + if (httpCode != null) { + cambriaErrorResponse.setHttpCode(httpCode); + switch (httpCode.intValue()) { + + case 401: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR); + break; + case 409: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST); + break; + case 500: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR); + break; + default: + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); + } + } else { + + boolean found = false; + Throwable throwable = e.getCause(); + if (throwable != null) { + String message = throwable.getMessage(); + + Throwable cause = throwable.getCause(); + + if (cause != null) { + Class clazz = cause.getClass(); + String className = clazz.getName(); + if (className.endsWith("UnknownHostException")) { + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR); + cambriaErrorResponse.addVariable(message); + found = true; + } + } + } + + if (false == found) { + cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); + cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + + return cambriaErrorResponse; + } + + /** + * write the error to the log + * + * @param cambriaErrorResponse + * @param errorMessage + * @param methodName + * @param operationDesc + */ + private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) { + + String httpCode = cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode()); + + switch (cambriaErrorResponse.getOperationStatus()) { + case UNKNOWN_HOST_ERROR: + String hostname = cambriaErrorResponse.getVariables().get(0); + BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode); + break; + case AUTHENTICATION_ERROR: + BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode); + break; + case CONNNECTION_ERROR: + BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode); + break; + + case INTERNAL_SERVER_ERROR: + BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc); + break; + default: + break; + } + + } + + /** + * create a topic if it does not exists in the topicsList + * + * @param hostSet + * - list of U-EB servers + * @param apiKey + * @param secretKey + * @param topicName + * - topic to create + * @param partitionCount + * @param replicationCount + * @return + */ + public CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) { + + CambriaTopicManager createTopicManager = null; + try { + + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey)); + + createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); + + } catch (HttpException | IOException | GeneralSecurityException e) { + + logger.debug("Failed to create topic {}", topicName, e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) { + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic"); + } + + return cambriaErrorResponse; + + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + return new CambriaErrorResponse(CambriaOperationStatus.OK); + + } + + public CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { + CambriaTopicManager createTopicManager = null; + try { + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); + + if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { + createTopicManager.revokeProducer(topicName, subscriberApiKey); + } else { + createTopicManager.revokeConsumer(topicName, subscriberApiKey); + } + + } catch (HttpObjectNotFoundException | GeneralSecurityException e) { + logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); + return cambriaErrorResponse; + + } catch (HttpException | IOException e) { + logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase()); + + return cambriaErrorResponse; + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + return cambriaErrorResponse; + } + + /** + * + * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER + * + * @param hostSet + * @param managerApiKey + * @param managerSecretKey + * @param subscriberApiKey + * @param subscriberTypeEnum + * @param topicName + * @return + */ + public CambriaErrorResponse registerToTopic(Collection hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) { + + CambriaTopicManager createTopicManager = null; + try { + createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); + + if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { + createTopicManager.allowProducer(topicName, subscriberApiKey); + } else { + createTopicManager.allowConsumer(topicName, subscriberApiKey); + } + + } catch (HttpObjectNotFoundException | GeneralSecurityException e) { + logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); + return cambriaErrorResponse; + + } catch (HttpException | IOException e) { + logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase()); + + return cambriaErrorResponse; + } finally { + if (createTopicManager != null) { + createTopicManager.close(); + } + } + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + return cambriaErrorResponse; + } + + /** + * create and retrieve a Cambria Consumer for a specific topic + * + * @param hostSet + * @param topicName + * @param apiKey + * @param secretKey + * @param consumerId + * @param consumerGroup + * @param timeoutMS + * @return + * @throws Exception + */ + public CambriaConsumer createConsumer(Collection hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception { + + CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHosts(hostSet).waitAtServer(timeoutMS).build(); + consumer.setApiCredentials(apiKey, secretKey); + return consumer; + } + + public void closeConsumer(CambriaConsumer consumer) { + + if (consumer != null) { + consumer.close(); + } + + } + + /** + * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error) + * + * @param topicConsumer + * @return + */ + public Either, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) { + + try { + Iterable messages = topicConsumer.fetch(); + if (messages == null) { + messages = new ArrayList(); + } + return Either.left(messages); + + } catch (IOException e) { + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + CambriaErrorResponse cambriaErrorResponse = processError(e); + + logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage()); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic"); + + return Either.right(cambriaErrorResponse); + + } catch (Exception e) { + logger.debug("Failed to fetch from U-EB topic", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); + return Either.right(cambriaErrorResponse); + } + } + + /** + * Publish notification message to a given queue + * + * @param topicName + * @param uebPublicKey + * @param uebSecretKey + * @param uebServers + * @param data + * @return + */ + public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data) { + + CambriaBatchingPublisher createSimplePublisher = null; + + try { + + String json = gson.toJson(data); + logger.trace("Before sending notification data {} to topic {}", json, topicName); + + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - private static final String PARTITION_KEY = "asdc" + "aa"; - - private final String SEND_NOTIFICATION = "send notification"; - - private Gson gson = new Gson(); - - public static boolean useHttpsWithDmaap = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().isUseHttpsWithDmaap(); + int result = createSimplePublisher.send(PARTITION_KEY, json); + try { + Thread.sleep(1 * 1000); + } catch (InterruptedException e) { + logger.debug("Failed during sleep after sending the message.", e); + } - /** - * process the response error from Cambria client - * - * @param message - * @return - */ - private Integer processMessageException(String message) { - - String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" }; - - Integer result = checkPattern(patterns[0], message, 2); - if (result != null) { - return result; - } - result = checkPattern(patterns[1], message, 2); - - return result; - - } - - /** - * check whether the message has a match with a given pattern inside it - * - * @param patternStr - * @param message - * @param groupIndex - * @return - */ - private Integer checkPattern(String patternStr, String message, int groupIndex) { - Integer result = null; - - Pattern pattern = Pattern.compile(patternStr); - Matcher matcher = pattern.matcher(message); - boolean find = matcher.find(); - if (find) { - String httpCode = matcher.group(groupIndex); - if (httpCode != null) { - try { - result = Integer.valueOf(httpCode); - } catch (NumberFormatException e) { - logger.debug("Failed to parse http code {}", httpCode); - } - } - } - return result; - } - - /** - * retrieve all topics from U-EB server - * - * @param hostSet - * @return - */ - public Either, CambriaErrorResponse> getTopics(List hostSet) { - - CambriaTopicManager createTopicManager = null; - try { - - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet)); - - Set topics = createTopicManager.getTopics(); - - if (topics == null || true == topics.isEmpty()) { - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null); - return Either.right(cambriaErrorResponse); - } - - return Either.left(topics); - - } catch (IOException | GeneralSecurityException e) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - logger.debug("Failed to fetch topics from U-EB server", e); - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics"); - - return Either.right(cambriaErrorResponse); - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - } - - /** - * process the error message from Cambria client. - * - * set Cambria status and http code in case we succeed to fetch it - * - * @return - */ - private CambriaErrorResponse processError(Exception e) { - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(); - - Integer httpCode = processMessageException(e.getMessage()); - - if (httpCode != null) { - cambriaErrorResponse.setHttpCode(httpCode); - switch (httpCode.intValue()) { - - case 401: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR); - break; - case 409: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST); - break; - case 500: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR); - break; - default: - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); - } - } else { - - boolean found = false; - Throwable throwable = e.getCause(); - if (throwable != null) { - String message = throwable.getMessage(); - - Throwable cause = throwable.getCause(); - - if (cause != null) { - Class clazz = cause.getClass(); - String className = clazz.getName(); - if (className.endsWith("UnknownHostException")) { - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR); - cambriaErrorResponse.addVariable(message); - found = true; - } - } - } - - if (false == found) { - cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR); - cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - } - - return cambriaErrorResponse; - } - - /** - * write the error to the log - * - * @param cambriaErrorResponse - * @param errorMessage - * @param methodName - * @param operationDesc - */ - private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) { - - String httpCode = (cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode())); - - switch (cambriaErrorResponse.getOperationStatus()) { - case UNKNOWN_HOST_ERROR: - String hostname = cambriaErrorResponse.getVariables().get(0); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebUnkownHostError, methodName, hostname); - BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode); - break; - case AUTHENTICATION_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebAuthenticationError, methodName, httpCode); - BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode); - break; - case CONNNECTION_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebConnectionError, methodName, httpCode); - BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode); - break; - - case INTERNAL_SERVER_ERROR: - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, methodName, operationDesc); - BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc); - break; - default: - break; - } - - } - - /** - * create a topic if it does not exists in the topicsList - * - * @param hostSet - * - list of U-EB servers - * @param apiKey - * @param secretKey - * @param topicName - * - topic to create - * @param partitionCount - * @param replicationCount - * @return - */ - public CambriaErrorResponse createTopic(Collection hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) { - - CambriaTopicManager createTopicManager = null; - try { - - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey)); - - createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount); - - } catch (HttpException | IOException | GeneralSecurityException e) { - - logger.debug("Failed to create topic {}", topicName, e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) { - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic"); - } - - return cambriaErrorResponse; - - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - return new CambriaErrorResponse(CambriaOperationStatus.OK); - - } - - public CambriaErrorResponse unRegisterFromTopic(Collection hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) { - CambriaTopicManager createTopicManager = null; - try { - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); - - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { - createTopicManager.revokeProducer(topicName, subscriberApiKey); - } else { - createTopicManager.revokeConsumer(topicName, subscriberApiKey); - } - - } catch (HttpObjectNotFoundException | GeneralSecurityException e) { - logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - return cambriaErrorResponse; - - } catch (HttpException | IOException e) { - logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase()); - - return cambriaErrorResponse; - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - return cambriaErrorResponse; - } - - /** - * - * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER - * - * @param hostSet - * @param topicName - * @param managerApiKey - * @param managerSecretKey - * @param subscriberApiKey - * @param subscriberTypeEnum - * @return - */ - public CambriaErrorResponse registerToTopic(Collection hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) { - - CambriaTopicManager createTopicManager = null; - try { - createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey)); - - if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) { - createTopicManager.allowProducer(topicName, subscriberApiKey); - } else { - createTopicManager.allowConsumer(topicName, subscriberApiKey); - } - - } catch (HttpObjectNotFoundException | GeneralSecurityException e) { - logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage()); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND); - return cambriaErrorResponse; - - } catch (HttpException | IOException e) { - logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase()); - - return cambriaErrorResponse; - } finally { - if (createTopicManager != null) { - createTopicManager.close(); - } - } - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - return cambriaErrorResponse; - } - - /** - * create and retrieve a Cambria Consumer for a specific topic - * - * @param hostSet - * @param topicName - * @param apiKey - * @param secretKey - * @param consumerId - * @param consumerGroup - * @param timeoutMS - * @return - * @throws Exception - */ - public CambriaConsumer createConsumer(Collection hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception { - - CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(hostSet).withSocketTimeout(timeoutMS).build(); - consumer.setApiCredentials(apiKey, secretKey); - return consumer; - } - - public void closeConsumer(CambriaConsumer consumer) { - - if (consumer != null) { - consumer.close(); - } - - } - - /** - * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error) - * - * @param topicConsumer - * @return - */ - public Either, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) { - - try { - Iterable messages = topicConsumer.fetch(); - if (messages == null) { - messages = new ArrayList(); - } - return Either.left(messages); - - } catch (IOException e) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - CambriaErrorResponse cambriaErrorResponse = processError(e); - - logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage()); - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic"); - - return Either.right(cambriaErrorResponse); - - } catch (Exception e) { - logger.debug("Failed to fetch from U-EB topic", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); - return Either.right(cambriaErrorResponse); - } - } + return response; - /** - * Publish notification message to a given queue - * - * @param topicName - * @param uebPublicKey - * @param uebSecretKey - * @param uebServers - * @param data - * @return - */ - public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data) { + } catch (IOException | GeneralSecurityException e) { + logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); - CambriaBatchingPublisher createSimplePublisher = null; + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); - try { + CambriaErrorResponse cambriaErrorResponse = processError(e); - String json = gson.toJson(data); - logger.trace("Before sending notification data {} to topic {}", json, topicName); + writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build(); - createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - - int result = createSimplePublisher.send(PARTITION_KEY, json); - - try { - Thread.sleep(1 * 1000); - } catch (InterruptedException e) { - logger.debug("Failed during sleep after sending the message.", e); - } - - logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - - CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - - return response; + return cambriaErrorResponse; + } finally { + if (createSimplePublisher != null) { + logger.debug("Before closing publisher"); + createSimplePublisher.close(); + logger.debug("After closing publisher"); + } + } + } - } catch (IOException | GeneralSecurityException e) { - logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); + public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data, long waitBeforeCloseTimeout) { - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + CambriaBatchingPublisher createSimplePublisher = null; - CambriaErrorResponse cambriaErrorResponse = processError(e); + CambriaErrorResponse response = null; + try { - writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION); + String json = gson.toJson(data); + logger.debug("Before sending notification data {} to topic {}", json, topicName); - return cambriaErrorResponse; - } finally { - if (createSimplePublisher != null) { - logger.debug("Before closing publisher"); - createSimplePublisher.close(); - logger.debug("After closing publisher"); - } - } - } + createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build(); + createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); - private String convertListToString(List list) { - StringBuilder builder = new StringBuilder(); + int result = createSimplePublisher.send(PARTITION_KEY, json); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - builder.append(list.get(i)); - if (i < list.size() - 1) { - builder.append(","); - } - } - } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + logger.debug("Failed during sleep after sending the message.", e); + } - return builder.toString(); - } + logger.debug("After sending notification data to topic {}. result is {}", topicName, result); - public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List uebServers, INotificationData data, long waitBeforeCloseTimeout) { + } catch (IOException | GeneralSecurityException e) { + logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); - CambriaBatchingPublisher createSimplePublisher = null; + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); - CambriaErrorResponse response = null; - try { + response = processError(e); - String json = gson.toJson(data); - logger.debug("Before sending notification data {} to topic {}", json, topicName); + writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION); - createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build(); - createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey); + return response; - int result = createSimplePublisher.send(PARTITION_KEY, json); + } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - logger.debug("Failed during sleep after sending the message.", e); - } + logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); + try { + List messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS); + if (messagesInQ != null && false == messagesInQ.isEmpty()) { + logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size()); + response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); + } else { + logger.debug("No message left in the queue after closing cambria publisher"); + response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + } + } catch (IOException | InterruptedException e) { + logger.debug("Failed to close cambria publisher", e); + response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); + } + logger.debug("After closing publisher"); - logger.debug("After sending notification data to topic {}. result is {}", topicName, result); + return response; - } catch (IOException | GeneralSecurityException e) { - logger.debug("Failed to send notification {} to topic {} ", data, topicName, e); + } - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); + public CambriaErrorResponse getApiKey(String server, String apiKey) { - response = processError(e); + CambriaErrorResponse response = null; - writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION); + List hostSet = new ArrayList<>(); + hostSet.add(server); + try { + CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); + createIdentityManager.getApiKey(apiKey); - return response; + response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - } + } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { + logger.debug("Failed to fetch api key {} from server {}", apiKey, server, e); - logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout); - try { - List messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS); - if (messagesInQ != null && false == messagesInQ.isEmpty()) { - logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size()); - response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); - } else { - logger.debug("No message left in the queue after closing cambria publisher"); - response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - } - } catch (IOException | InterruptedException e) { - logger.debug("Failed to close cambria publisher", e); - response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION); - } - logger.debug("After closing publisher"); + response = processError(e); - return response; + } - } + return response; + } - public CambriaErrorResponse getApiKey(String server, String apiKey) { + public Either createUebKeys(List hostSet) { + Either result; - CambriaErrorResponse response = null; + try { + CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); - List hostSet = new ArrayList<>(); - hostSet.add(server); - CambriaIdentityManager createIdentityManager = null; - try { - createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet)); - createIdentityManager.getApiKey(apiKey); - response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + String description = String.format("ASDC Key for %s", CONSUMER_ID); + ApiCredential credential = createIdentityManager.createApiKey("", description); + createIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret()); + result = Either.left(credential); - } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) { - logger.debug("Failed to fetch api key {} from server ", apiKey, server, e); + } catch (Exception e) { + logger.debug("Failed to create ueb keys for servers {}",hostSet, e); - response = processError(e); + result = Either.right(processError(e)); - } + } - return response; - } + return result; + } - private static T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder client) throws MalformedURLException, GeneralSecurityException { - if (useHttpsWithDmaap) { - client.usingHttps(); - } - return (T)client.build(); - } + @VisibleForTesting + T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder client) throws MalformedURLException, GeneralSecurityException { + return (T)client.build(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java new file mode 100644 index 0000000000..94fff3cfaa --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.api.DME2Manager; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.aft.dme2.iterator.factory.DME2EndpointIteratorFactory; + +import org.springframework.stereotype.Component; + +@Component +public class DME2EndpointIteratorCreator { + + public DME2EndpointIterator create(String lookupURI) throws DME2Exception { + // Initializing DME2Manager instance + DME2Manager manager = DME2Manager.getDefaultInstance(); + // Returning an instance of the DME2EndpointIteratorFactory + return (DME2EndpointIterator) DME2EndpointIteratorFactory.getInstance().getIterator(lookupURI, null, null, manager); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java deleted file mode 100644 index 5e4c08275f..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.distribution.engine; - -public enum DeConfigurationStatus { - - OK(""), MISSING_CONFIGURATION(""); - - private String description; - - DeConfigurationStatus(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java index bd3d74e323..7d2d4680b5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java @@ -20,361 +20,340 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.util.YamlToObjectConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Matcher; +import java.util.regex.Pattern; @Component("distributionEngine") public class DistributionEngine implements IDistributionEngine { - public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); - - public static void main(String[] args) { - - List servers = new ArrayList<>(); - - servers.add("uebsb91kcdc.it.att.com:3904"); - servers.add("uebsb91kcdc.it.att.com:3904"); - servers.add("uebsb91kcdc.it.att.com:3904"); - - YamlToObjectConverter converter = new YamlToObjectConverter(); - DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class); - - DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null); - distributionEngineInitTask.startTask(); - - } - - @javax.annotation.Resource - private ComponentsUtils componentUtils; - - @javax.annotation.Resource - private DistributionNotificationSender distributionNotificationSender; - - @javax.annotation.Resource - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - - @javax.annotation.Resource - private DistributionEngineClusterHealth distributionEngineClusterHealth; - - private static Logger logger = LoggerFactory.getLogger(DistributionEngine.class.getName()); - - private Map envNamePerInitTask = new HashMap(); - private Map envNamePerPollingTask = new HashMap(); - - private Map envNamePerStatus = new HashMap(); - - @Override - public boolean isActive() { - - if (true == envNamePerInitTask.isEmpty()) { - return false; - } - - for (DistributionEngineInitTask task : envNamePerInitTask.values()) { - boolean active = task.isActive(); - if (active == false) { - return false; - } - } - return true; - } - - @PostConstruct - private void init() { - - logger.trace("Enter init method of DistributionEngine"); - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine(); - logger.debug("Distribution engine activation parameter is {}", startDistributionEngine); - if (false == startDistributionEngine) { - logger.info("The disribution engine is disabled"); - - this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled(); - - return; - } - - boolean isValidConfig = validateConfiguration(distributionEngineConfiguration); - - if (false == isValidConfig) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); - - this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError(); - return; - } - - List environments = distributionEngineConfiguration.getEnvironments(); - - for (String envName : environments) { - - DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(distributionEngineConfiguration, envName, componentUtils, distributionEngineClusterHealth); - - logger.debug("Init task for environment {}", envName); - - AtomicBoolean status = new AtomicBoolean(false); - envNamePerStatus.put(envName, status); - DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask); - distributionEngineInitTask.startTask(); - envNamePerInitTask.put(envName, distributionEngineInitTask); - envNamePerPollingTask.put(envName, distributionEnginePollingTask); - } - - logger.debug("Init UEB health check"); - distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); - - logger.trace("Exit init method of DistributionEngine"); - - } - - @PreDestroy - public void shutdown() { - logger.info("distribution engine shutdown - start"); - if (envNamePerInitTask != null) { - for (DistributionEngineInitTask task : envNamePerInitTask.values()) { - task.destroy(); - } - } - if (envNamePerPollingTask != null) { - for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) { - task.destroy(); - } - } - - } - - /** - * validate mandatory configuration parameters received - * - * @param deConfiguration - * @return - */ - protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) { - - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - boolean result = true; - result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result; - result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result; - result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result; - result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result; - result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result; - result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result; - result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result; - result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result; - result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result; - result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result; - - return result; - } - - private boolean isValidServers(List uebServers, String methodName, String paramName) { - - if (uebServers == null || uebServers.size() == 0) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - - if (uebServers.size() < 2) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeConfigurationInvalidListSizeError, methodName, paramName, "2"); - BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2); - return false; - } - - for (String serverFqdn : uebServers) { - if (false == isValidFqdn(serverFqdn)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, methodName, paramName, serverFqdn); - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn); - return false; - } - } - - return true; - } - - private boolean isValidFqdn(String serverFqdn) { - - try { - Matcher matcher = FQDN_PATTERN.matcher(serverFqdn); - return matcher.matches(); - - } catch (Exception e) { - logger.debug("Failed to match value of address {}", serverFqdn, e); - return false; - } - - } - - private boolean isEmptyParam(String param) { - - if (param == null || true == param.isEmpty()) { - return true; - } - - return false; - } - - private boolean isValidParam(String paramValue, String methodName, String paramName) { - - if (isEmptyParam(paramValue)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isValidParam(List paramValue, String methodName, String paramName) { - - if (isEmptyList(paramValue)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isValidObject(Object paramValue, String methodName, String paramName) { - - if (paramValue == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName); - BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); - return false; - } - return true; - - } - - private boolean isEmptyList(List list) { - if (list == null || true == list.isEmpty()) { - return true; - } - return false; - } - - private String getEnvironmentErrorDescription(StorageOperationStatus status) { - - switch (status) { - case DISTR_ENVIRONMENT_NOT_AVAILABLE: - return "environment is unavailable"; - case DISTR_ENVIRONMENT_NOT_FOUND: - return "environment is not configured in our system"; - case DISTR_ENVIRONMENT_SENT_IS_INVALID: - return "environment name is invalid"; - - default: - return "unkhown"; - - } - } - - public StorageOperationStatus isEnvironmentAvailable(String envName) { - - if (envName == null || true == envName.isEmpty()) { - - return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID; - } - - AtomicBoolean status = envNamePerStatus.get(envName); - if (status == null) { - return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND; - } - - if (false == status.get()) { - return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE; - } - return StorageOperationStatus.OK; - } + private static final Logger LOGGER = LoggerFactory.getLogger(DistributionEngine.class); + private static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE); - public StorageOperationStatus isEnvironmentAvailable() { + @Autowired + private EnvironmentsEngine environmentsEngine; - String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + @Resource + private DistributionNotificationSender distributionNotificationSender; - return isEnvironmentAvailable(envName); - } + @Resource + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Override - public void disableEnvironment(String envName) { - // TODO disable tasks - AtomicBoolean status = envNamePerStatus.get(envName); - status.set(false); - } + @Resource + private DistributionEngineClusterHealth distributionEngineClusterHealth; - @Override - public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + @Resource + private ServiceDistributionValidation serviceDistributionValidation; - logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); + private Map envNamePerInitTask = new HashMap<>(); + private Map envNamePerPollingTask = new HashMap<>(); + private Map envNamePerStatus = new HashMap<>(); - DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + /** + * The main method for testing only + * @param args + */ + public static void main(String[] args) { - String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName(); - String topicName = DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName); + List servers = new ArrayList<>(); + String server = "uebsb91kcdc.it.att.com:3904"; + servers.add(server); + servers.add(server); + servers.add(server); - StorageOperationStatus sendNotification = distributionNotificationSender.sendNotification(topicName, distributionId, deConfiguration, envName, notificationData, service, userId, modifierName); + YamlToObjectConverter converter = new YamlToObjectConverter(); + DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class); - logger.debug("Finish notifyService. status is {}", sendNotification); + DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null, null); + distributionEngineInitTask.startTask(); + + } - return sendNotification; - } + @Override + public boolean isActive() { - @Override - public Either isReadyForDistribution(Service service, String distributionId, String envName) { - StorageOperationStatus status = isEnvironmentAvailable(envName); - if (status != StorageOperationStatus.OK) { - String envErrorDec = getEnvironmentErrorDescription(status); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, - "Environment name " + envName + " is not available. Reason : " + envErrorDec); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec); - return Either.right(status); - } + if (envNamePerInitTask.isEmpty()) { + return false; + } - Either isServiceContainsDeploymentArtifactsStatus = serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service); - if (isServiceContainsDeploymentArtifactsStatus.isRight()) { - StorageOperationStatus operationStatus = isServiceContainsDeploymentArtifactsStatus.right().value(); - return Either.right(operationStatus); - } else { - Boolean isDeploymentArtifactExists = isServiceContainsDeploymentArtifactsStatus.left().value(); - if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) { - return Either.right(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND); - } - } + for (DistributionEngineInitTask task : envNamePerInitTask.values()) { + boolean active = task.isActive(); + if (!active) { + return false; + } + } + return true; + } - INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId); - value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service); + @PostConstruct + private void init() { + + LOGGER.trace("Enter init method of DistributionEngine"); + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine(); + LOGGER.debug("Distribution engine activation parameter is {}", startDistributionEngine); + if (!startDistributionEngine) { + LOGGER.info("The disribution engine is disabled"); - return Either.left(value); - } + this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled(); + + return; + } + + boolean isValidConfig = validateConfiguration(distributionEngineConfiguration); + + if (!isValidConfig) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase"); + + this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError(); + return; + } + + List environments = distributionEngineConfiguration.getEnvironments(); + + for (String envName : environments) { + LOGGER.debug("init task for environment {}", envName); + AtomicBoolean status = new AtomicBoolean(false); + envNamePerStatus.put(envName, status); + environmentsEngine.connectUebTopicForDistributionConfTopic(envName, status, envNamePerInitTask, envNamePerPollingTask); + } + + LOGGER.debug("init UEB health check"); + distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + + LOGGER.trace("Exit init method of DistributionEngine"); + + } + + @PreDestroy + public void shutdown() { + LOGGER.info("distribution engine shutdown - start"); + if (envNamePerInitTask != null) { + for (DistributionEngineInitTask task : envNamePerInitTask.values()) { + task.destroy(); + } + } + if (envNamePerPollingTask != null) { + for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) { + task.destroy(); + } + } + + } + + /** + * validate mandatory configuration parameters received + * + * @param deConfiguration + * @return + */ + protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) { + + String methodName = "validateConfiguration"; + + boolean result = true; + result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result; + result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result; + result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result; + result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result; + result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result; + result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result; + result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result; + result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result; + result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result; + result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result; + + return result; + } + + private boolean isValidServers(List uebServers, String methodName, String paramName) { + + if (uebServers == null || uebServers.isEmpty()) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + + if (uebServers.size() < 2) { + BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2); + return false; + } + + for (String serverFqdn : uebServers) { + if (!isValidFqdn(serverFqdn)) { + BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn); + return false; + } + } + + return true; + } + + private boolean isValidFqdn(String serverFqdn) { + + try { + Matcher matcher = FQDN_PATTERN.matcher(serverFqdn); + return matcher.matches(); + + } catch (Exception e) { + LOGGER.debug("Failed to match value of address {}", serverFqdn, e); + return false; + } + } + + private boolean isValidParam(String paramValue, String methodName, String paramName) { + + if (StringUtils.isEmpty(paramValue)) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + } + + private boolean isValidParam(List paramValue, String methodName, String paramName) { + + if (CollectionUtils.isEmpty(paramValue)) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + } + + private boolean isValidObject(Object paramValue, String methodName, String paramName) { + + if (paramValue == null) { + BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName); + return false; + } + return true; + + } + + private String getEnvironmentErrorDescription(StorageOperationStatus status) { + + switch (status) { + case DISTR_ENVIRONMENT_NOT_AVAILABLE: + return "environment is unavailable"; + case DISTR_ENVIRONMENT_NOT_FOUND: + return "environment is not configured in our system"; + case DISTR_ENVIRONMENT_SENT_IS_INVALID: + return "environment name is invalid"; + default: + return "unkhown"; + } + } + + @Override + public StorageOperationStatus isEnvironmentAvailable(String envName) { + + if (envName == null || envName.isEmpty()) { + + return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID; + } + + AtomicBoolean status = envNamePerStatus.get(envName); + if (status == null) { + return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND; + } + + if (!status.get()) { + return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE; + } + return StorageOperationStatus.OK; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable() { + + String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + + return isEnvironmentAvailable(envName); + } + + @Override + public void disableEnvironment(String envName) { + AtomicBoolean status = envNamePerStatus.get(envName); + status.set(false); + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + return notifyService(distributionId, service, notificationData, envName, envName, userId, modifierName); + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) { + LOGGER.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName); + String topicName = buildTopicName(envName); + ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId)) + .map(EnvironmentMessageBusData::new) + .map(messageBusData -> distributionNotificationSender.sendNotification(topicName, distributionId, messageBusData, notificationData, service, userId, modifierName)) + .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE); + LOGGER.debug("Finish notifyService. status is {}", notifyServiceStatus); + return notifyServiceStatus; + } + + private String buildTopicName(String envName) { + DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName(); + return DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName); + } + + @Override + public StorageOperationStatus isReadyForDistribution(Service service, String envName) { + StorageOperationStatus status = isEnvironmentAvailable(envName); + if (status != StorageOperationStatus.OK) { + String envErrorDec = getEnvironmentErrorDescription(status); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec); + return status; + } + + return verifyServiceHasDeploymentArtifacts(service); + } + + @Override + public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) { + if (!serviceDistributionArtifactsBuilder.verifyServiceContainsDeploymentArtifacts(service)) { + return StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND; + } + return StorageOperationStatus.OK; + } + + @Override + public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) { + return environmentsEngine.getEnvironmentById(opEnvId); + } + + @Override + public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) { + INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId, workloadContext); + value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service); + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java index 85a868f156..9599879006 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java @@ -20,22 +20,6 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; @@ -47,311 +31,318 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; + @Component("distribution-engine-cluster-health") public class DistributionEngineClusterHealth { - protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck"; + protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck"; - private static Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT); + private static final Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT); - private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; + private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck"; - boolean lastHealthState = false; + boolean lastHealthState = false; - Object lockOject = new Object(); + Object lockOject = new Object(); - private long reconnectInterval = 5; + private long reconnectInterval = 5; - private long healthCheckReadTimeout = 20; + private long healthCheckReadTimeout = 20; - private static Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class); - private List uebServers = null; + private List uebServers = null; - private String publicApiKey = null; + private String publicApiKey = null; - public enum HealthCheckInfoResult { + public enum HealthCheckInfoResult { - OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), - UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), - NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), - DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); + OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())), + NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())), + DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())); - private HealthCheckInfo healthCheckInfo; + private HealthCheckInfo healthCheckInfo; - HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { - this.healthCheckInfo = healthCheckInfo; - } + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } - public HealthCheckInfo getHealthCheckInfo() { - return healthCheckInfo; - } + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } - } + } - private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); - private Map envNamePerStatus = null; + private Map envNamePerStatus = null; - private ScheduledFuture scheduledFuture = null; + private ScheduledFuture scheduledFuture = null; - ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "UEB-Health-Check-Task"); - } - }); + ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "UEB-Health-Check-Task"); + } + }); - HealthCheckScheduledTask healthCheckScheduledTask = null; + HealthCheckScheduledTask healthCheckScheduledTask = null; - public enum ClusterStatusDescription { + public enum ClusterStatusDescription { - OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"); + OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"); - private String desc; + private String desc; - ClusterStatusDescription(String desc) { - this.desc = desc; - } + ClusterStatusDescription(String desc) { + this.desc = desc; + } - public String getDescription() { - return desc; - } + public String getDescription() { + return desc; + } - } + } - /** - * Health Check Task Scheduler. - * - * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server. - * - * - * @author esofer - * - */ - public class HealthCheckScheduledTask implements Runnable { + /** + * Health Check Task Scheduler. + * + * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server. + * + * + * @author esofer + * + */ + public class HealthCheckScheduledTask implements Runnable { - List healthCheckCalls = new ArrayList<>(); + List healthCheckCalls = new ArrayList<>(); - public HealthCheckScheduledTask(List uebServers) { + public HealthCheckScheduledTask(List uebServers) { - logger.debug("Create health check calls for servers {}", uebServers); - if (uebServers != null) { - for (String server : uebServers) { - healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey)); - } - } - } + logger.debug("Create health check calls for servers {}", uebServers); + if (uebServers != null) { + for (String server : uebServers) { + healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey)); + } + } + } - @Override - public void run() { + @Override + public void run() { - healthLogger.trace("Executing UEB Health Check Task - Start"); + healthLogger.trace("Executing UEB Health Check Task - Start"); - boolean healthStatus = verifyAtLeastOneEnvIsUp(); + boolean healthStatus = verifyAtLeastOneEnvIsUp(); - if (true == healthStatus) { - boolean queryUebStatus = queryUeb(); - if (queryUebStatus == lastHealthState) { - return; - } + if (true == healthStatus) { + boolean queryUebStatus = queryUeb(); + if (queryUebStatus == lastHealthState) { + return; + } - synchronized (lockOject) { - if (queryUebStatus != lastHealthState) { - logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); - lastHealthState = queryUebStatus; - logAlarm(lastHealthState); - if (true == queryUebStatus) { - healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); - } else { - healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); - } - } - } - } else { - healthLogger.trace("Not all UEB Environments are up"); - } - - } - - /** - * verify that at least one environment is up. - * - */ - private boolean verifyAtLeastOneEnvIsUp() { - - boolean healthStatus = false; + synchronized (lockOject) { + if (queryUebStatus != lastHealthState) { + logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); + lastHealthState = queryUebStatus; + logAlarm(lastHealthState); + if (true == queryUebStatus) { + healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); + } else { + healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + } + } + } + } else { + healthLogger.trace("Not all UEB Environments are up"); + } + + } + + /** + * verify that at least one environment is up. + * + */ + private boolean verifyAtLeastOneEnvIsUp() { + + boolean healthStatus = false; - if (envNamePerStatus != null) { - Collection values = envNamePerStatus.values(); - if (values != null) { - for (AtomicBoolean status : values) { - if (true == status.get()) { - healthStatus = true; - break; - } - } - } - } - - return healthStatus; - } - - /** - * executor for the query itself - */ - ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "UEB-Health-Check-Thread"); - } - }); - - /** - * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers. - * - * - * @return - */ - private boolean queryUeb() { - - Boolean result = false; - int retryNumber = 1; - for (UebHealthCheckCall healthCheckCall : healthCheckCalls) { - try { - - healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer()); - - Future future = healthCheckExecutor.submit(healthCheckCall); - result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS); - - healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result); - - if (result != null && true == result.booleanValue()) { - break; - } - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message); - healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e); - } - retryNumber++; - - } - - return result; - - } - - public List getHealthCheckCalls() { - return healthCheckCalls; - } - - } - - @PostConstruct - private void init() { - - logger.trace("Enter init method of DistributionEngineClusterHealth"); - - Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds(); - if (reconnectIntervalConfig != null) { - reconnectInterval = reconnectIntervalConfig.longValue(); - } - Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout(); - if (healthCheckReadTimeoutConfig != null) { - healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue(); - } - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - this.uebServers = distributionEngineConfiguration.getUebServers(); - this.publicApiKey = distributionEngineConfiguration.getUebPublicKey(); - - this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers); - - logger.trace("Exit init method of DistributionEngineClusterHealth"); - - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (healthCheckScheduler != null) { - healthCheckScheduler.shutdown(); - } - - } - - /** - * Start health check task. - * - * @param envNamePerStatus - * @param startTask - */ - public void startHealthCheckTask(Map envNamePerStatus, boolean startTask) { - this.envNamePerStatus = envNamePerStatus; - - if (startTask == true && this.scheduledFuture == null) { - this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); - } - } - - public void startHealthCheckTask(Map envNamePerStatus) { - startHealthCheckTask(envNamePerStatus, true); - } - - private void logAlarm(boolean lastHealthState) { - if (lastHealthState == true) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery, UEB_HEALTH_CHECK_STR); - BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, UEB_HEALTH_CHECK_STR); - BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR); - } - } - - public HealthCheckInfo getHealthCheckInfo() { - return healthCheckInfo; - } - - /** - * change the health check to DISABLE - */ - public void setHealthCheckUebIsDisabled() { - healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo(); - } - - /** - * change the health check to NOT CONFGIURED - */ - public void setHealthCheckUebConfigurationError() { - healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo(); - } - - public void setHealthCheckOkAndReportInCaseLastStateIsDown() { - - if (lastHealthState == true) { - return; - } - synchronized (lockOject) { - if (lastHealthState == false) { - logger.debug("Going to update health check state to available"); - lastHealthState = true; - healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); - logAlarm(lastHealthState); - } - } - - } + if (envNamePerStatus != null) { + Collection values = envNamePerStatus.values(); + if (values != null) { + for (AtomicBoolean status : values) { + if (true == status.get()) { + healthStatus = true; + break; + } + } + } + } + + return healthStatus; + } + + /** + * executor for the query itself + */ + ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "UEB-Health-Check-Thread"); + } + }); + + /** + * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers. + * + * + * @return + */ + private boolean queryUeb() { + + Boolean result = false; + int retryNumber = 1; + for (UebHealthCheckCall healthCheckCall : healthCheckCalls) { + try { + + healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer()); + + Future future = healthCheckExecutor.submit(healthCheckCall); + result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS); + + healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result); + + if (result != null && true == result.booleanValue()) { + break; + } + + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message); + healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e); + } + retryNumber++; + + } + + return result; + + } + + public List getHealthCheckCalls() { + return healthCheckCalls; + } + + } + + @PostConstruct + protected void init() { + + logger.trace("Enter init method of DistributionEngineClusterHealth"); + + Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds(); + if (reconnectIntervalConfig != null) { + reconnectInterval = reconnectIntervalConfig.longValue(); + } + Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout(); + if (healthCheckReadTimeoutConfig != null) { + healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue(); + } + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + this.uebServers = distributionEngineConfiguration.getUebServers(); + this.publicApiKey = distributionEngineConfiguration.getUebPublicKey(); + + this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers); + + logger.trace("Exit init method of DistributionEngineClusterHealth"); + + } + + @PreDestroy + protected void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (healthCheckScheduler != null) { + healthCheckScheduler.shutdown(); + } + + } + + /** + * Start health check task. + * + * @param envNamePerStatus + * @param startTask + */ + public void startHealthCheckTask(Map envNamePerStatus, boolean startTask) { + this.envNamePerStatus = envNamePerStatus; + + if (startTask == true && this.scheduledFuture == null) { + this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS); + } + } + + public void startHealthCheckTask(Map envNamePerStatus) { + startHealthCheckTask(envNamePerStatus, true); + } + + private void logAlarm(boolean lastHealthState) { + if (lastHealthState == true) { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR); + } + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + + /** + * change the health check to DISABLE + */ + public void setHealthCheckUebIsDisabled() { + healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo(); + } + + /** + * change the health check to NOT CONFGIURED + */ + public void setHealthCheckUebConfigurationError() { + healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo(); + } + + public void setHealthCheckOkAndReportInCaseLastStateIsDown() { + + if (lastHealthState == true) { + return; + } + synchronized (lockOject) { + if (lastHealthState == false) { + logger.debug("Going to update health check state to available"); + lastHealthState = true; + healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo(); + logAlarm(lastHealthState); + } + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java index 1eeaa1229e..1759f69b3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java @@ -20,274 +20,268 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; public class DistributionEngineInitTask implements Runnable { - public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine"; - public static final String ALREADY_EXISTS = "ALREADY_EXISTS"; - public static final String CONSUMER = "CONSUMER"; - public static final String PRODUCER = "PRODUCER"; - public static final String CREATED = "CREATED"; - public static final String FAILED = "FAILED"; - public static final Integer HTTP_OK = 200; - - private Long delayBeforeStartFlow = 0l; - private DistributionEngineConfiguration deConfiguration; - private String envName; - private long retryInterval; - private long currentRetryInterval; - private long maxInterval; - // private boolean active = false; - boolean maximumRetryInterval = false; - private AtomicBoolean status = null; - ComponentsUtils componentsUtils = null; - DistributionEnginePollingTask distributionEnginePollingTask = null; - - private CambriaHandler cambriaHandler = new CambriaHandler(); - - public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask) { - super(); - this.delayBeforeStartFlow = delayBeforeStartFlow; - this.deConfiguration = deConfiguration; - this.envName = envName; - this.retryInterval = deConfiguration.getInitRetryIntervalSec(); - this.currentRetryInterval = retryInterval; - this.maxInterval = deConfiguration.getInitMaxIntervalSec(); - this.status = status; - this.componentsUtils = componentsUtils; - this.distributionEnginePollingTask = distributionEnginePollingTask; - } - - private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); - - private static Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class.getName()); - - ScheduledFuture scheduledFuture = null; - - public void startTask() { - if (scheduledExecutorService != null) { - Integer retryInterval = deConfiguration.getInitRetryIntervalSec(); - logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow); - this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS); - - } - } - - public void restartTask() { - - this.stopTask(); - - logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval); - - long lastCurrentInterval = currentRetryInterval; - incrementRetryInterval(); - - this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS); - - } - - protected void incrementRetryInterval() { - if (currentRetryInterval < maxInterval) { - currentRetryInterval *= 2; - if (currentRetryInterval > maxInterval) { - setMaxRetryInterval(); - } - } else { - setMaxRetryInterval(); - } - } - - private void setMaxRetryInterval() { - currentRetryInterval = maxInterval; - maximumRetryInterval = true; - logger.debug("Set next retry init interval to {}", maxInterval); - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - logger.debug("Stop reinit task. result = {}", result); - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); - } - scheduledFuture = null; - } - } - - public void destroy() { - this.stopTask(); - if (scheduledExecutorService != null) { - scheduledExecutorService.shutdown(); - } - } - - @Override - public void run() { - - boolean result = false; - result = initFlow(); - - if (true == result) { - this.stopTask(); - this.status.set(true); - if (this.distributionEnginePollingTask != null) { - String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName); - logger.debug("start polling distribution status topic {}", topicName); - this.distributionEnginePollingTask.startTask(topicName); - } - } else { - if (false == maximumRetryInterval) { - this.restartTask(); - } - } - } - - /** - * run initialization flow - * - * @return - */ - public boolean initFlow() { - - logger.trace("Start init flow for environment {}", this.envName); - - Set topicsList = null; - Either, CambriaErrorResponse> getTopicsRes = null; - - getTopicsRes = cambriaHandler.getTopics(deConfiguration.getUebServers()); - if (getTopicsRes.isRight()) { - CambriaErrorResponse status = getTopicsRes.right().value(); - if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) { - topicsList = new HashSet<>(); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); - - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); - - return false; - } - } else { - topicsList = getTopicsRes.left().value(); - } - - String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName); - logger.debug("Going to handle topic {}", notificationTopic); - - boolean status = createTopicIfNotExists(topicsList, notificationTopic); - if (false == status) { - return false; - } - - CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER); - - CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus(); - - if (createStatus != CambriaOperationStatus.OK) { - return false; - } - - String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName); - logger.debug("Going to handle topic {}", statusTopic); - status = createTopicIfNotExists(topicsList, statusTopic); - if (false == status) { - return false; - } - - CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER); - - if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) { - return false; - } - - return true; - } - - private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) { - CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(deConfiguration.getUebServers(), topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebPublicKey(), subscriberType); - - String role = CONSUMER; - if (subscriberType == SubscriberTypeEnum.PRODUCER) { - role = PRODUCER; - } - auditRegistration(topicName, registerStatus, role); - return registerStatus; - } - - private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) { - if (componentsUtils != null) { - Integer httpCode = registerProducerStatus.getHttpCode(); - String httpCodeStr = String.valueOf(httpCode); - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, deConfiguration.getUebPublicKey(), httpCodeStr); - } - } - - private boolean createTopicIfNotExists(Set topicsList, String topicName) { - - if (topicsList.contains(topicName)) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); - } - return true; - } - - CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(deConfiguration.getUebServers(), deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(), - deConfiguration.getCreateTopic().getReplicationCount()); - - CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus(); - if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); - } - } else if (status == CambriaOperationStatus.OK) { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED); - } - } else { - if (componentsUtils != null) { - this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED); - } - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); - - BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); - - return false; - } - - return true; - } - - public static String buildTopicName(String topicName, String environment) { - return topicName + "-" + environment.toUpperCase(); - } - - public boolean isActive() { - return this.status.get(); - } - - public long getCurrentRetryInterval() { - return currentRetryInterval; - } - - protected void setCambriaHandler(CambriaHandler cambriaHandler) { - this.cambriaHandler = cambriaHandler; - } + public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine"; + public static final String ALREADY_EXISTS = "ALREADY_EXISTS"; + public static final String CONSUMER = "CONSUMER"; + public static final String PRODUCER = "PRODUCER"; + public static final String CREATED = "CREATED"; + public static final String FAILED = "FAILED"; + public static final Integer HTTP_OK = 200; + + private Long delayBeforeStartFlow = 0l; + private DistributionEngineConfiguration deConfiguration; + private String envName; + private long retryInterval; + private long currentRetryInterval; + private long maxInterval; + boolean maximumRetryInterval = false; + private AtomicBoolean status = null; + ComponentsUtils componentsUtils = null; + DistributionEnginePollingTask distributionEnginePollingTask = null; + private OperationalEnvironmentEntry environmentEntry; + + private CambriaHandler cambriaHandler = new CambriaHandler(); + + public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) { + super(); + this.delayBeforeStartFlow = delayBeforeStartFlow; + this.deConfiguration = deConfiguration; + this.envName = envName; + this.retryInterval = deConfiguration.getInitRetryIntervalSec(); + this.currentRetryInterval = retryInterval; + this.maxInterval = deConfiguration.getInitMaxIntervalSec(); + this.status = status; + this.componentsUtils = componentsUtils; + this.distributionEnginePollingTask = distributionEnginePollingTask; + this.environmentEntry = environmentEntry; + } + + private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); + + private static final Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class); + + ScheduledFuture scheduledFuture = null; + + public void startTask() { + if (scheduledExecutorService != null) { + Integer retryInterval = deConfiguration.getInitRetryIntervalSec(); + logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow); + this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS); + + } + } + + public void restartTask() { + + this.stopTask(); + + logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval); + + long lastCurrentInterval = currentRetryInterval; + incrementRetryInterval(); + + this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS); + + } + + protected void incrementRetryInterval() { + if (currentRetryInterval < maxInterval) { + currentRetryInterval *= 2; + if (currentRetryInterval > maxInterval) { + setMaxRetryInterval(); + } + } else { + setMaxRetryInterval(); + } + } + + private void setMaxRetryInterval() { + currentRetryInterval = maxInterval; + maximumRetryInterval = true; + logger.debug("Set next retry init interval to {}", maxInterval); + } + + public void stopTask() { + if (scheduledFuture != null) { + boolean result = scheduledFuture.cancel(true); + logger.debug("Stop reinit task. result = {}", result); + if (false == result) { + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task"); + } + scheduledFuture = null; + } + } + + public void destroy() { + this.stopTask(); + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + } + } + + @Override + public void run() { + + boolean result = false; + result = initFlow(); + + if (true == result) { + this.stopTask(); + this.status.set(true); + if (this.distributionEnginePollingTask != null) { + String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName); + logger.debug("start polling distribution status topic {}", topicName); + this.distributionEnginePollingTask.startTask(topicName); + } + } else { + if (false == maximumRetryInterval) { + this.restartTask(); + } + } + } + + /** + * run initialization flow + * + * @return + */ + public boolean initFlow() { + + logger.trace("Start init flow for environment {}", this.envName); + + Set topicsList = null; + Either, CambriaErrorResponse> getTopicsRes = null; + + getTopicsRes = cambriaHandler.getTopics(environmentEntry.getDmaapUebAddress().stream().collect(Collectors.toList())); + if (getTopicsRes.isRight()) { + CambriaErrorResponse status = getTopicsRes.right().value(); + if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) { + topicsList = new HashSet<>(); + } else { + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server"); + return false; + } + } else { + topicsList = getTopicsRes.left().value(); + } + + String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName); + logger.debug("Going to handle topic {}", notificationTopic); + + boolean status = createTopicIfNotExists(topicsList, notificationTopic); + if (false == status) { + return false; + } + + CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER); + + CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus(); + + if (createStatus != CambriaOperationStatus.OK) { + return false; + } + + String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName); + logger.debug("Going to handle topic {}", statusTopic); + status = createTopicIfNotExists(topicsList, statusTopic); + if (false == status) { + return false; + } + + CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER); + + if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) { + return false; + } + + return true; + } + + private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) { + CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), environmentEntry.getUebApikey(), subscriberType, topicName); + + String role = CONSUMER; + if (subscriberType == SubscriberTypeEnum.PRODUCER) { + role = PRODUCER; + } + auditRegistration(topicName, registerStatus, role); + return registerStatus; + } + + private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) { + if (componentsUtils != null) { + Integer httpCode = registerProducerStatus.getHttpCode(); + String httpCodeStr = String.valueOf(httpCode); + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, environmentEntry.getUebApikey(), httpCodeStr); + } + } + + private boolean createTopicIfNotExists(Set topicsList, String topicName) { + + if (topicsList.contains(topicName)) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); + } + return true; + } + + CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(), + deConfiguration.getCreateTopic().getReplicationCount()); + + CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus(); + if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS); + } + } else if (status == CambriaOperationStatus.OK) { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED); + } + } else { + if (componentsUtils != null) { + this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED); + } + BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName); + return false; + } + + return true; + } + + public static String buildTopicName(String topicName, String environment) { + return topicName + "-" + environment.toUpperCase(); + } + + public boolean isActive() { + return this.status.get(); + } + + public long getCurrentRetryInterval() { + return currentRetryInterval; + } + + protected void setCambriaHandler(CambriaHandler cambriaHandler) { + this.cambriaHandler = cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java index fc7c473d6b..b4f4863284 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java @@ -20,188 +20,189 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - +import com.att.nsa.cambria.client.CambriaConsumer; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; public class DistributionEnginePollingTask implements Runnable { - public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling"; - - private String topicName; - private ComponentsUtils componentUtils; - private int fetchTimeoutInSec = 15; - private int pollingIntervalInSec; - private String consumerId; - private String consumerGroup; - private DistributionEngineConfiguration distributionEngineConfiguration; - - private CambriaHandler cambriaHandler = new CambriaHandler(); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build()); - - private static Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class.getName()); - - ScheduledFuture scheduledFuture = null; - private CambriaConsumer cambriaConsumer = null; - - private DistributionEngineClusterHealth distributionEngineClusterHealth = null; - - public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, String envName, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth) { - - this.componentUtils = componentUtils; - this.distributionEngineConfiguration = distributionEngineConfiguration; - DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic(); - this.pollingIntervalInSec = statusConfig.getPollingIntervalSec(); - this.fetchTimeoutInSec = statusConfig.getFetchTimeSec(); - this.consumerGroup = statusConfig.getConsumerGroup(); - this.consumerId = statusConfig.getConsumerId(); - this.distributionEngineClusterHealth = distributionEngineClusterHealth; - } - - public void startTask(String topicName) { - - this.topicName = topicName; - logger.debug("start task for polling topic {}", topicName); - if (fetchTimeoutInSec < 15) { - logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default"); - fetchTimeoutInSec = 15; - } - try { - cambriaConsumer = cambriaHandler.createConsumer(distributionEngineConfiguration.getUebServers(), topicName, distributionEngineConfiguration.getUebPublicKey(), distributionEngineConfiguration.getUebSecretKey(), consumerId, consumerGroup, - fetchTimeoutInSec * 1000); - - if (scheduledPollingService != null) { - logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec); - scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS); - - } - } catch (Exception e) { - logger.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); - } - } - - public void stopTask() { - if (scheduledFuture != null) { - boolean result = scheduledFuture.cancel(true); - logger.debug("Stop polling task. result = {}", result); - if (false == result) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); - } - scheduledFuture = null; - } - if (cambriaConsumer != null) { - logger.debug("close consumer"); - cambriaHandler.closeConsumer(cambriaConsumer); - } - - } - - public void destroy() { - this.stopTask(); - shutdownExecutor(); - } - - @Override - public void run() { - logger.trace("run() method. polling queue {}", topicName); - - try { - // init error - if (cambriaConsumer == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); - stopTask(); - return; - } - - Either, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer); - // fetch error - if (fetchResult.isRight()) { - CambriaErrorResponse errorResponse = fetchResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value()); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value()); - - // TODO: if status== internal error (connection problem) change - // state to inactive - // in next try, if succeed - change to active - return; - } - - // success - Iterable messages = fetchResult.left().value(); - for (String message : messages) { - logger.trace("received message {}", message); - try { - DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class); - componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(), - String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason()); - - distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown(); - - } catch (Exception e) { - logger.debug("failed to convert message to object", e); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); - BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); - } - - } - } catch (Exception e) { - logger.debug("unexpected error occured", e); - String methodName = new Object() { - }.getClass().getEnclosingMethod().getName(); - - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage()); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); - } - - } - - private void shutdownExecutor() { - if (scheduledPollingService == null) - return; - - scheduledPollingService.shutdown(); // Disable new tasks from being - // submitted - try { - // Wait a while for existing tasks to terminate - if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) { - scheduledPollingService.shutdownNow(); // Cancel currently - // executing tasks - // Wait a while for tasks to respond to being cancelled - if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) - logger.debug("Pool did not terminate"); - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - scheduledPollingService.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } + public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling"; + + private String topicName; + private ComponentsUtils componentUtils; + private int fetchTimeoutInSec = 15; + private int pollingIntervalInSec; + private String consumerId; + private String consumerGroup; + + private CambriaHandler cambriaHandler = new CambriaHandler(); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private DistributionCompleteReporter distributionCompleteReporter; + + private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build()); + + private static final Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class); + + ScheduledFuture scheduledFuture = null; + private CambriaConsumer cambriaConsumer = null; + + private DistributionEngineClusterHealth distributionEngineClusterHealth = null; + + private OperationalEnvironmentEntry environmentEntry; + + public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) { + + this.componentUtils = componentUtils; + DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic(); + this.pollingIntervalInSec = statusConfig.getPollingIntervalSec(); + this.fetchTimeoutInSec = statusConfig.getFetchTimeSec(); + this.consumerGroup = statusConfig.getConsumerGroup(); + this.consumerId = statusConfig.getConsumerId(); + this.distributionEngineClusterHealth = distributionEngineClusterHealth; + this.environmentEntry = environmentEntry; + this.distributionCompleteReporter = distributionCompleteReporter; + } + + public void startTask(String topicName) { + + this.topicName = topicName; + logger.debug("start task for polling topic {}", topicName); + if (fetchTimeoutInSec < 15) { + logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default"); + fetchTimeoutInSec = 15; + } + try { + cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup, + fetchTimeoutInSec * 1000); + + if (scheduledPollingService != null) { + logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec); + scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS); + + } + } catch (Exception e) { + logger.debug("unexpected error occured", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + } + } + + public void stopTask() { + if (scheduledFuture != null) { + boolean result = scheduledFuture.cancel(true); + logger.debug("Stop polling task. result = {}", result); + if (false == result) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task"); + } + scheduledFuture = null; + } + if (cambriaConsumer != null) { + logger.debug("close consumer"); + cambriaHandler.closeConsumer(cambriaConsumer); + } + + } + + public void destroy() { + this.stopTask(); + shutdownExecutor(); + } + + @Override + public void run() { + logger.trace("run() method. polling queue {}", topicName); + + try { + // init error + if (cambriaConsumer == null) { + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly"); + stopTask(); + return; + } + + Either, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer); + // fetch error + if (fetchResult.isRight()) { + CambriaErrorResponse errorResponse = fetchResult.right().value(); + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse); + + // TODO: if status== internal error (connection problem) change + // state to inactive + // in next try, if succeed - change to active + return; + } + + // success + Iterable messages = fetchResult.left().value(); + for (String message : messages) { + logger.trace("received message {}", message); + try { + DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class); + handleDistributionNotificationMsg(notification); + distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown(); + } catch (Exception e) { + logger.debug("failed to convert message to object", e); + BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value()); + } + + } + } catch (Exception e) { + logger.debug("unexpected error occured", e); + String methodName = new Object() { + }.getClass().getEnclosingMethod().getName(); + + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage()); + } + + } + + private void handleDistributionNotificationMsg(DistributionStatusNotification notification) { + componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(), + String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason()); + if (notification.isDistributionCompleteNotification()) { + distributionCompleteReporter.reportDistributionComplete(notification); + } + } + + private void shutdownExecutor() { + if (scheduledPollingService == null) + return; + + scheduledPollingService.shutdown(); // Disable new tasks from being + // submitted + try { + // Wait a while for existing tasks to terminate + if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) { + scheduledPollingService.shutdownNow(); // Cancel currently + // executing tasks + // Wait a while for tasks to respond to being cancelled + if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) + logger.debug("Pool did not terminate"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + scheduledPollingService.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java index 16a0a1dc31..62af4b8514 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java @@ -20,20 +20,13 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionException; - -import javax.annotation.PreDestroy; - import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -41,79 +34,83 @@ import org.springframework.stereotype.Component; @Component("distributionNotificationSender") public class DistributionNotificationSender { - protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending"; - - private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName()); - - // final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; - // final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL - // + "resources/%s/%s/artifacts/%s"; - // final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; - - @javax.annotation.Resource - InterfaceLifecycleOperation interfaceLifecycleOperation; - - @javax.annotation.Resource - protected ComponentsUtils componentUtils; - - ExecutorService executorService = null; - - CambriaHandler cambriaHandler = new CambriaHandler(); - - NotificationExecutorService notificationExecutorService = new NotificationExecutorService(); - - public DistributionNotificationSender() { - super(); - - DistributionNotificationTopicConfig distributionNotificationTopic = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic(); - - executorService = notificationExecutorService.createExcecutorService(distributionNotificationTopic); - } - - @PreDestroy - public void shutdown() { - logger.debug("Going to close notificationExecutorService"); - if (executorService != null) { - - long maxWaitingTime = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds(); - - notificationExecutorService.shutdownAndAwaitTermination(executorService, maxWaitingTime + 1); - } - } - - public StorageOperationStatus sendNotification(String topicName, String distributionId, DistributionEngineConfiguration deConfiguration, String envName, INotificationData notificationData, Service service, String userId, String modifierName) { - - Runnable task = new PublishNotificationRunnable(envName, distributionId, service, notificationData, deConfiguration, topicName, userId, modifierName, cambriaHandler, componentUtils, ThreadLocalsHolder.getUuid()); - try { - executorService.submit(task); - } catch (RejectedExecutionException e) { - logger.warn("Failed to submit task. Number of threads exceeeds", e); - return StorageOperationStatus.OVERLOAD; - } - - return StorageOperationStatus.OK; - } - - /** - * Audit the publishing notification in case of internal server error. - * - * @param topicName - * @param status - * @param distributionId - * @param envName - */ - private void auditDistributionNotificationInternalServerError(String topicName, StorageOperationStatus status, String distributionId, String envName) { - - if (this.componentUtils != null) { - this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, "", " ", "Service", " ", " ", " ", envName, " ", topicName, distributionId, "Error: Internal Server Error. " + status, " "); - } - } - - protected CambriaErrorResponse publishNotification(INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName) { - - CambriaErrorResponse status = cambriaHandler.sendNotification(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data); + protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending"; + + private static final Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class); + + @javax.annotation.Resource + protected ComponentsUtils componentUtils; + private CambriaHandler cambriaHandler = new CambriaHandler(); + private DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); + + public ActionStatus sendNotification(String topicName, String distributionId, EnvironmentMessageBusData messageBusData, INotificationData notificationData, Service service, String userId, String modifierName) { + long startTime = System.currentTimeMillis(); + CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, messageBusData.getUebPublicKey(), messageBusData.getUebPrivateKey(), messageBusData.getDmaaPuebEndpoints(), notificationData, + deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds()); + logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode()); + auditDistributionNotification(topicName, distributionId, status, service, messageBusData.getEnvId(), userId, modifierName, notificationData.getWorkloadContext(), messageBusData.getTenant()); + long endTime = System.currentTimeMillis(); + logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime)); + return convertCambriaResponse(status); + } + + private void auditDistributionNotification(String topicName, String distributionId, CambriaErrorResponse status, Service service, String envId, String userId, String modifierName, String workloadContext, String tenant) { + if (this.componentUtils != null) { + Integer httpCode = status.getHttpCode(); + String httpCodeStr = String.valueOf(httpCode); + + String desc = getDescriptionFromErrorResponse(status); + + this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envId, service.getLifecycleState().name(), topicName, + distributionId, desc, httpCodeStr, workloadContext, tenant); + } + } + + private String getDescriptionFromErrorResponse(CambriaErrorResponse status) { + + CambriaOperationStatus operationStatus = status.getOperationStatus(); + + switch (operationStatus) { + case OK: + return "OK"; + case AUTHENTICATION_ERROR: + return "Error: Authentication problem towards U-EB server"; + case INTERNAL_SERVER_ERROR: + return "Error: Internal U-EB server error"; + case UNKNOWN_HOST_ERROR: + return "Error: Cannot reach U-EB server host"; + case CONNNECTION_ERROR: + return "Error: Cannot connect to U-EB server"; + case OBJECT_NOT_FOUND: + return "Error: object not found in U-EB server"; + default: + return "Error: Internal Cambria server problem"; + + } + + } + + private ActionStatus convertCambriaResponse(CambriaErrorResponse status) { + CambriaOperationStatus operationStatus = status.getOperationStatus(); + + switch (operationStatus) { + case OK: + return ActionStatus.OK; + case AUTHENTICATION_ERROR: + return ActionStatus.AUTHENTICATION_ERROR; + case INTERNAL_SERVER_ERROR: + return ActionStatus.GENERAL_ERROR; + case UNKNOWN_HOST_ERROR: + return ActionStatus.UNKNOWN_HOST; + case CONNNECTION_ERROR: + return ActionStatus.CONNNECTION_ERROR; + case OBJECT_NOT_FOUND: + return ActionStatus.OBJECT_NOT_FOUND; + default: + return ActionStatus.GENERAL_ERROR; + + } + } - return status; - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java index 73a0336361..006aa26082 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java @@ -22,63 +22,67 @@ package org.openecomp.sdc.be.components.distribution.engine; public class DistributionStatusNotification { - String distributionID; - String consumerID; - long timestamp; - String artifactURL; - DistributionStatusNotificationEnum status; - String errorReason; - - public String getDistributionID() { - return distributionID; - } - - public void setDistributionID(String distributionId) { - this.distributionID = distributionId; - } - - public String getConsumerID() { - return consumerID; - } - - public void setConsumerID(String consumerId) { - this.consumerID = consumerId; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public DistributionStatusNotificationEnum getStatus() { - return status; - } - - public void setStatus(DistributionStatusNotificationEnum status) { - this.status = status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } - - @Override - public String toString() { - return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; - } + String distributionID; + String consumerID; + long timestamp; + String artifactURL; + DistributionStatusNotificationEnum status; + String errorReason; + + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionId) { + this.distributionID = distributionId; + } + + public String getConsumerID() { + return consumerID; + } + + public void setConsumerID(String consumerId) { + this.consumerID = consumerId; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public DistributionStatusNotificationEnum getStatus() { + return status; + } + + public void setStatus(DistributionStatusNotificationEnum status) { + this.status = status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } + + public boolean isDistributionCompleteNotification() { + return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK.equals(status) || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR.equals(status); + } + + @Override + public String toString() { + return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java index bd77f3915a..65aa18ee97 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine; public enum DistributionStatusNotificationEnum { - DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED + DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED, COMPONENT_DONE_ERROR, COMPONENT_DONE_OK, DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java new file mode 100644 index 0000000000..3d35a84d7a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRClientFactory; +import com.att.nsa.mr.client.MRConsumer; +import fj.data.Either; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.security.SecurityUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; + +/** + * Allows to create DMAAP client of type MRConsumer according received configuration parameters + */ +@Component("dmaapClientFactory") +public class DmaapClientFactory { + private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class); + + /** + * Creates DMAAP consumer according to received parameters + * @param parameters + * @return an instance object of type MRConsumer + * @throws IOException + */ + public MRConsumer create(DmaapConsumerConfiguration parameters) throws Exception { + MRConsumer consumer = MRClientFactory.createConsumer(buildProperties(parameters)); + logger.info("MRConsumer created for topic {}", parameters.getTopic()); + return consumer; + } + + private Properties buildProperties(DmaapConsumerConfiguration parameters) throws Exception{ + Properties props = new Properties(); + Either passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() ); + if (passkey.isRight()){ + throw new GeneralSecurityException("invalid password, cannot build properties"); + } + props.setProperty("Latitude", Double.toString(parameters.getLatitude())); + props.setProperty("Longitude", Double.toString(parameters.getLongitude())); + props.setProperty("Version", parameters.getVersion()); + props.setProperty("ServiceName", parameters.getServiceName()); + props.setProperty("Environment", parameters.getEnvironment()); + props.setProperty("Partner", parameters.getPartner()); + props.setProperty("routeOffer", parameters.getRouteOffer()); + props.setProperty("Protocol", parameters.getProtocol()); + props.setProperty("username", parameters.getCredential().getUsername()); + props.setProperty("password", passkey.left().value() ); + props.setProperty("contenttype", parameters.getContenttype()); + props.setProperty("host", parameters.getHosts()); + props.setProperty("topic", parameters.getTopic()); + props.setProperty("group", parameters.getConsumerGroup()); + props.setProperty("id", parameters.getConsumerId()); + props.setProperty("timeout", Integer.toString(parameters.getTimeoutMs())); + props.setProperty("limit", Integer.toString(parameters.getLimit())); + props.setProperty("AFT_DME2_REQ_TRACE_ON", Boolean.toString(parameters.isDme2TraceOn())); + props.setProperty("AFT_ENVIRONMENT", parameters.getAftEnvironment()); + props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs())); + props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs())); + props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs())); + + String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath(); + ensureFileExists(dme2PreferredRouterFilePath); + props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath); + + props.setProperty("TransportType", "DME2"); + props.setProperty("SubContextPath", "/"); + props.setProperty("MethodType", "GET"); + props.setProperty("authKey", ""); + props.setProperty("authDate", ""); + props.setProperty("filter", ""); + props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", ""); + props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", ""); + props.setProperty("sessionstickinessrequired", "no"); + + return props; + } + + private void ensureFileExists(String filePath) throws IOException { + File file = new File(filePath); + if(file.createNewFile()) { + logger.info("The file {} has been created on the disk", file.getAbsolutePath()); + } + else{ + logger.info("The file {} already exists", file.getAbsolutePath()); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java new file mode 100644 index 0000000000..e0661f4b22 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRConsumer; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * Allows consuming DMAAP topic according to received consumer parameters + * Allows processing received messages. + */ +@Service +public class DmaapConsumer { + private final ExecutorFactory executorFactory; + private final DmaapClientFactory dmaapClientFactory; + private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class); + + @Autowired + private DmaapHealth dmaapHealth; + /** + * Allows to create an object of type DmaapConsumer + * @param executorFactory + * @param dmaapClientFactory + */ + @Autowired + public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory) { + this.executorFactory = executorFactory; + this.dmaapClientFactory = dmaapClientFactory; + } + + /** + * Allows consuming DMAAP topic according to received consumer parameters + * @param notificationReceived + * @param exceptionHandler + * @throws Exception + */ + public void consumeDmaapTopic(Consumer notificationReceived, UncaughtExceptionHandler exceptionHandler) throws Exception { + + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); + String topic = dmaapConsumerParams.getTopic(); + logger.info("Starting to consume topic {} for DMAAP consumer with the next parameters {}. ", topic, dmaapConsumerParams); + MRConsumer consumer = dmaapClientFactory.create(dmaapConsumerParams); + ScheduledExecutorService pollExecutor = executorFactory.createScheduled(topic + "Client"); + ExecutorService notificationExecutor = executorFactory.create(topic + "Consumer", exceptionHandler); + + pollExecutor.scheduleWithFixedDelay(() -> { + logger.info("Trying to fetch messages from topic: {}", topic); + boolean isTopicAvailable = false; + try { + Iterable messages = consumer.fetch(); + isTopicAvailable = true ; + if (messages != null) { + for (String msg : messages) { + logger.info("The DMAAP message {} received. The topic is {}.", msg, topic); + notificationExecutor.execute(() -> notificationReceived.accept(msg)); + } + } + //successfully fetched + } + catch (Exception e) { + logger.error("The exception {} occured upon fetching DMAAP message", e); + } + dmaapHealth.report( isTopicAvailable ); + }, 0L, dmaapConsumerParams.getPollingInterval(), TimeUnit.SECONDS); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java new file mode 100644 index 0000000000..ba5e9f7c9c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java @@ -0,0 +1,220 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.commons.validator.routines.UrlValidator; +import org.apache.http.client.utils.URIUtils; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.apache.commons.lang3.StringUtils.*; +import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE; + +@Component("dmaapHealth") +public class DmaapHealth { + + + protected static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaap.healthcheck"; + private static final String DMAAP_HEALTH_CHECK_STR = "dmaapHealthCheck"; + private static final Logger log = LoggerFactory.getLogger(DmaapHealth.class); + private static final Logger logHealth = LoggerFactory.getLogger(DMAAP_HEALTH_LOG_CONTEXT); + private HealthCheckInfo healthCheckInfo = DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo(); + private long healthCheckReadTimeout = 20; + private long reconnectInterval = 5; + private HealthCheckScheduledTask healthCheckScheduledTask = null ; + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + private ScheduledFuture scheduledFuture = null; + private DmaapConsumerConfiguration configuration = null ; + + private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false); + private volatile AtomicBoolean reportedHealthState = null; + + public enum HealthCheckInfoResult { + OK(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())), + UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())), + DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription())); + + private HealthCheckInfo healthCheckInfo; + HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) { + this.healthCheckInfo = healthCheckInfo; + } + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + } + + public enum DmaapStatusDescription { + OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong "); + + private String desc; + DmaapStatusDescription(String desc) { + this.desc = desc; + } + public String getDescription() { + return desc; + } + + } + + @PostConstruct + public DmaapHealth init() { + log.trace("Enter init method of Dmaap health"); + synchronized (DmaapHealth.class){ + this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration(); + + Integer pollingInterval = configuration.getPollingInterval(); + if (pollingInterval != null && pollingInterval!=0) { + reconnectInterval = pollingInterval; + } + Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs(); + if (healthCheckReadTimeoutConfig != null) { + this.healthCheckReadTimeout = healthCheckReadTimeoutConfig; + } + this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other + startHealthCheckTask(true); + } + log.trace("Exit init method of DistributionEngineClusterHealth"); + return this; + } + + @PreDestroy + protected void destroy() { + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + if (scheduler != null) { + scheduler.shutdown(); + } + } + + /** + * Start health check task. + * + * @param startTask + */ + public void startHealthCheckTask( boolean startTask ) { + synchronized (DmaapHealth.class){ + if (startTask && this.scheduledFuture == null) { + this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS); + } + } + } + + public void report(Boolean isUp){ + if (reportedHealthState == null) + reportedHealthState = new AtomicBoolean(isUp); + reportedHealthState.set(isUp); + } + + public void logAlarm(boolean lastHealthState) { + try{ + if ( lastHealthState ) { + BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR ); + } else { + BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR ); + } + }catch( Exception e ){ + log.debug("cannot logAlarm -> {}" ,e ); + } + } + + public DmaapConsumerConfiguration getConfiguration() { + return configuration; + } + + public HealthCheckInfo getHealthCheckInfo() { + return healthCheckInfo; + } + + /** + * Health Check Task Scheduler - infinite check. + */ + public class HealthCheckScheduledTask implements Runnable { + private final DmaapConsumerConfiguration config; + private static final int timeout = 8192; + + public HealthCheckScheduledTask(final DmaapConsumerConfiguration config){ + this.config = config; + } + @Override + public void run() { + logHealth.trace("Executing Dmaap Health Check Task - Start"); + boolean prevIsReachable = false; + boolean reachable = false; + //first try simple ping + try{ + if ( reportedHealthState != null ){ + reachable = reportedHealthState.get(); + } + else{ + reachable = false; + } + prevIsReachable = lastHealthState.getAndSet( reachable ); + healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo; + } + catch( Exception e ){ + log.debug("{} | cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e ); + prevIsReachable = lastHealthState.getAndSet(false); + healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo; + } + if (prevIsReachable != lastHealthState.get()) + logAlarm( lastHealthState.get() ); + } + + + /** + * @deprecated (health is reported outside from EnvironmentEngine consumer fetch) + */ + @Deprecated + public boolean isICMPReachable( ) throws IOException{ + try{ + String hostname = getUrlHost(config.getHosts()); + return InetAddress.getByName( hostname ).isReachable(timeout); + }catch( URISyntaxException e ){ + log.debug("{} | malformed host configuration -> ",DMAAP_HEALTH_CHECK_STR , e); + } + return false; + } + } + + public static String getUrlHost(String qualifiedHost) throws URISyntaxException{ + //region - parse complex format ex. + try{ + UrlValidator validator = new UrlValidator(); + if (validator.isValid(qualifiedHost)){ + return URIUtils.extractHost(new URI(qualifiedHost)).getHostName(); + }else{ + log.debug("{} | invalid url format, continuing ", DMAAP_HEALTH_CHECK_STR ); + } + }catch(URISyntaxException e){ + log.debug("{} | invalid url format, continuing {} ", DMAAP_HEALTH_CHECK_STR , e); + } + //endregion + + //region - try shortcut format or + if ( countMatches( qualifiedHost , ":") <= 1){ + String[] address = qualifiedHost.split(":"); + if ( address.length>0 && isNotBlank(address[0]) ){ + return address[0]; + } + } + //endregion + throw new URISyntaxException( qualifiedHost , "invalid hostname, expecting a single , (valid ex. www.google.com:80 | www.google.com | http:\\\\www.google.com:8181)"); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java new file mode 100644 index 0000000000..3f86fe73de --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.distribution.engine; + +/* Example { + "operationalEnvironmentId": "28122015552391", + "operationalEnvironmentName": "Operational Environment Name", + "operationalEnvironmentType": "ECOMP", + "tenantContext": "TEST", + "workloadContext": "ECOMP_E2E-IST", + "action": "Create" + }*/ +public class DmaapNotificationDataImpl implements IDmaapNotificationData, IDmaapAuditNotificationData { + + private String operationalEnvironmentId; + private String operationalEnvironmentType; + private String action; + private String operationalEnvironmentName; + private String tenantContext; + + @Override + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + @Override + public OperationaEnvironmentTypeEnum getOperationalEnvironmentType() { + return OperationaEnvironmentTypeEnum.findByName(operationalEnvironmentType); + } + + @Override + public DmaapActionEnum getAction() { + return DmaapActionEnum.findByName(action); + } + + @Override + public String getOperationalEnvironmentName() { + return operationalEnvironmentName; + } + + @Override + public String getTenantContext() { + return tenantContext; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java new file mode 100644 index 0000000000..67977b6361 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.ArrayList; +import java.util.List; + +/** + * a pojo which holds all the necessary data to communicate with the message bus + * this class is a reflection ot the {@link OperationalEnvironmentEntry} class + */ +public class EnvironmentMessageBusData { + + private List dmaaPuebEndpoints; + + private String uebPublicKey; + + private String uebPrivateKey; + + private String envId; + + private String tenant; + + public EnvironmentMessageBusData() { + } + + public EnvironmentMessageBusData(OperationalEnvironmentEntry operationalEnvironment) { + this.dmaaPuebEndpoints = new ArrayList<>(operationalEnvironment.getDmaapUebAddress()); + this.uebPublicKey = operationalEnvironment.getUebApikey(); + this.uebPrivateKey = operationalEnvironment.getUebSecretKey(); + this.envId = operationalEnvironment.getEnvironmentId(); + this.tenant = operationalEnvironment.getTenant(); + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public List getDmaaPuebEndpoints() { + return dmaaPuebEndpoints; + } + + public void setDmaaPuebEndpoints(List dmaaPuebEndpoints) { + this.dmaaPuebEndpoints = dmaaPuebEndpoints; + } + + public String getUebPublicKey() { + return uebPublicKey; + } + + public void setUebPublicKey(String uebPublicKey) { + this.uebPublicKey = uebPublicKey; + } + + public String getUebPrivateKey() { + return uebPrivateKey; + } + + public void setUebPrivateKey(String uebPrivateKey) { + this.uebPrivateKey = uebPrivateKey; + } + + public String getEnvId() { + return envId; + } + + public void setEnvId(String envId) { + this.envId = envId; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java new file mode 100644 index 0000000000..822464c631 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java @@ -0,0 +1,526 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.aft.dme2.iterator.domain.DME2EndpointReference; +import com.att.aft.dme2.manager.registry.DME2Endpoint; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.DmaapActionEnum; +import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.OperationaEnvironmentTypeEnum; +import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.be.config.DmeConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut; + +/** + * Allows to consume DMAAP topic and handle received notifications + */ +@Service +public class EnvironmentsEngine implements INotificationHandler { + + private static final String MESSAGE_BUS = "MessageBus"; + private static final String UNKNOWN = "Unknown"; + private static final Logger log = LoggerFactory.getLogger(EnvironmentsEngine.class); + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); + + private Map environments; + private Map envNamePerStatus = new HashMap<>(); + private Map envNamePerPollingTask = new HashMap<>(); + private Map envNamePerInitTask = new HashMap<>(); + + private final DmaapConsumer dmaapConsumer; + private final OperationalEnvironmentDao operationalEnvironmentDao; + private final DME2EndpointIteratorCreator epIterCreator; + private final AaiRequestHandler aaiRequestHandler; + private final ComponentsUtils componentUtils; + private final CambriaHandler cambriaHandler; + private final DistributionEngineClusterHealth distributionEngineClusterHealth; + private final DistributionCompleteReporter distributionCompleteReporter; + + public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao, DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils, CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth, DistributionCompleteReporter distributionCompleteReporter) { + this.dmaapConsumer = dmaapConsumer; + this.operationalEnvironmentDao = operationalEnvironmentDao; + this.epIterCreator = epIterCreator; + this.aaiRequestHandler = aaiRequestHandler; + this.componentUtils = componentUtils; + this.cambriaHandler = cambriaHandler; + this.distributionEngineClusterHealth = distributionEngineClusterHealth; + this.distributionCompleteReporter = distributionCompleteReporter; + } + + @VisibleForTesting + @PostConstruct + void init() { + log.trace("Environments engine has been initialized. "); + try { + environments = populateEnvironments(); + createUebTopicsForEnvironments(); + dmaapConsumer.consumeDmaapTopic(this::handleMessage, + (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e)); + } + catch (Exception e) { + log.error("An error occurred upon consuming topic by Dmaap consumer client." , e); + } + } + public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry, + AtomicBoolean status, + Map envNamePerInitTask, Map envNamePerPollingTask){ + connectUebTopic(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask); + + } + + public void connectUebTopicForDistributionConfTopic(String envName, + AtomicBoolean status, + Map envNamePerInitTask, Map envNamePerPollingTask){ + connectUebTopic(environments.get(envName), status, envNamePerInitTask, envNamePerPollingTask); + + } + /** + * Allows to create and run UEB initializing and polling tasks + * @param status + * @param envNamePerInitTask + * @param envNamePerPollingTask + * @param opEnvEntry + */ + private void connectUebTopic(OperationalEnvironmentEntry opEnvEntry, AtomicBoolean status, + Map envNamePerInitTask, + Map envNamePerPollingTask) { + + String envId = opEnvEntry.getEnvironmentId(); + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask( + distributionEngineConfiguration, distributionCompleteReporter, componentUtils, distributionEngineClusterHealth, + opEnvEntry); + String envName = configurationManager.getDistributionEngineConfiguration().getEnvironments().get(0); + DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, + distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask, + opEnvEntry); + distributionEngineInitTask.startTask(); + envNamePerInitTask.put(envId, distributionEngineInitTask); + envNamePerPollingTask.put(envId, distributionEnginePollingTask); + + log.debug("Environment envId = {} has been connected to the UEB topic", envId); + } + + @Override + public boolean handleMessage(String notification) { + DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager() + .getConfiguration().getDmaapConsumerConfiguration(); + Supplier supplier = () -> handleMessageLogic(notification); + Either eitherTimeOut = runMethodWithTimeOut(supplier, + dmaapConsumerParams.getTimeLimitForNotificationHandleMs()); + + boolean result; + if (eitherTimeOut.isRight()) { + result = false; + } else { + result = eitherTimeOut.left().value(); + } + return result; + } + + public boolean handleMessageLogic(String notification) { + Wrapper errorWrapper = new Wrapper<>(); + Wrapper opEnvEntryWrapper = new Wrapper<>(); + try { + + log.debug("handle message - for operational environment notification received: {}", notification); + Gson gsonObj = new GsonBuilder().create(); + + IDmaapNotificationData notificationData = gsonObj.fromJson(notification, + DmaapNotificationDataImpl.class); + IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification, + DmaapNotificationDataImpl.class); + + AuditingActionEnum actionEnum; + switch(notificationData.getAction()) { + case CREATE: + actionEnum = AuditingActionEnum.CREATE_ENVIRONMENT; + break; + case UPDATE: + actionEnum = AuditingActionEnum.UPDATE_ENVIRONMENT; + break; + case DELETE: + actionEnum = AuditingActionEnum.DELETE_ENVIRONMENT; + break; + default: + actionEnum = AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION; + break; + } + componentUtils.auditEnvironmentEngine(actionEnum, + notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(), + notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(), + auditNotificationData.getTenantContext()); + + if (errorWrapper.isEmpty()) { + validateNotification(errorWrapper, notificationData, auditNotificationData); + } + // Perform Save In-Progress Dao + if (errorWrapper.isEmpty()) { + saveEntryWithInProgressStatus(errorWrapper, opEnvEntryWrapper, notificationData); + } + + if (errorWrapper.isEmpty()) { + buildOpEnv(errorWrapper, opEnvEntryWrapper.getInnerElement()); + } + + } catch (Exception e) { + log.debug("handle message for operational environmet failed for notification: {} with error :{}", + notification, e.getMessage(), e); + errorWrapper.setInnerElement(false); + + } + return errorWrapper.isEmpty(); + } + + private void validateNotification(Wrapper errorWrapper, IDmaapNotificationData notificationData, + IDmaapAuditNotificationData auditNotificationData) { + // Check OperationaEnvironmentType + if (errorWrapper.isEmpty()) { + validateEnvironmentType(errorWrapper, notificationData, auditNotificationData); + } + // Check Action Type + if (errorWrapper.isEmpty()) { + validateActionType(errorWrapper, notificationData); + } + // Check is valid for create/update (not In-Progress state) + if (errorWrapper.isEmpty()) { + validateState(errorWrapper, notificationData); + } + } + + public void buildOpEnv(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + // Get Env Info From A&AI + if (errorWrapper.isEmpty()) { + retrieveOpEnvInfoFromAAI(errorWrapper, opEnvEntry); + } + + if (errorWrapper.isEmpty()) { + // Get List Of UEB Addresses From AFT_DME + retrieveUebAddressesFromAftDme(errorWrapper, opEnvEntry); + } + + // Create UEB keys and set them on EnvEntry + if (errorWrapper.isEmpty()) { + createUebKeys(errorWrapper, opEnvEntry); + } + + // Create Topics + if (errorWrapper.isEmpty()) { + log.debug("handle message - Create Topics"); + createUebTopicsForEnvironment(opEnvEntry); + } + + // Save Status Complete and Add to Map + if (errorWrapper.isEmpty()) { + saveEntryWithCompleteStatus(errorWrapper, opEnvEntry); + } + + // Update Environments Map + if (errorWrapper.isEmpty()) { + environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry); + } + else{ + saveEntryWithFailedStatus(errorWrapper, opEnvEntry); + } + } + + private void saveEntryWithFailedStatus(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - save OperationalEnvironment Failed Status"); + opEnvEntry.setStatus(EnvironmentStatusEnum.FAILED); + saveOpEnvEntry(errorWrapper, opEnvEntry); + } + + void saveEntryWithCompleteStatus(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - save OperationalEnvironment Complete Dao"); + opEnvEntry.setStatus(EnvironmentStatusEnum.COMPLETED); + saveOpEnvEntry(errorWrapper, opEnvEntry); + + } + + void retrieveUebAddressesFromAftDme(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Get List Of UEB Addresses From AFT_DME"); + try { + boolean isKeyFieldsValid = !isEmpty(opEnvEntry.getTenant()) && !isEmpty(opEnvEntry.getEcompWorkloadContext()); + if( isKeyFieldsValid ){ + String opEnvKey = map2OpEnvKey(opEnvEntry); + String environmentId = opEnvEntry.getEnvironmentId(); + List uebHosts = discoverUebHosts(opEnvKey, environmentId); + opEnvEntry.setDmaapUebAddress(uebHosts.stream().collect(Collectors.toSet())); + } + else{ + errorWrapper.setInnerElement(false); + log.debug("Can Not Build AFT DME Key from workLoad & Tenant Fields."); + } + + } catch (DME2Exception e) { + errorWrapper.setInnerElement(false); + log.error("Failed to retrieve Ueb Addresses From DME. ", e); + } + } + + void createUebKeys(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Create UEB keys"); + List discoverEndPoints = opEnvEntry.getDmaapUebAddress().stream() + .collect(Collectors.toList()); + Either eitherCreateUebKeys = cambriaHandler + .createUebKeys(discoverEndPoints); + if (eitherCreateUebKeys.isRight()) { + errorWrapper.setInnerElement(false); + log.debug("handle message - failed to create UEB Keys"); + } else { + ApiCredential apiCredential = eitherCreateUebKeys.left().value(); + opEnvEntry.setUebApikey(apiCredential.getApiKey()); + opEnvEntry.setUebSecretKey(apiCredential.getApiSecret()); + } + } + + void retrieveOpEnvInfoFromAAI(Wrapper errorWrapper, OperationalEnvironmentEntry opEnvEntry) { + log.debug("handle message - Get Env Info From A&AI"); + Either eitherOperationalEnvInfo = getOperationalEnvById( + opEnvEntry.getEnvironmentId()); + if (eitherOperationalEnvInfo.isRight()) { + errorWrapper.setInnerElement(false); + log.debug("handle message - failed to retrieve details from A&AI"); + } else { + OperationalEnvInfo operationalEnvInfo = eitherOperationalEnvInfo.left().value(); + opEnvEntry.setEcompWorkloadContext(operationalEnvInfo.getWorkloadContext()); + opEnvEntry.setTenant(operationalEnvInfo.getTenantContext()); + } + } + + void saveEntryWithInProgressStatus(Wrapper errorWrapper, Wrapper opEnvEntryWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - save OperationalEnvironment In-Progress Dao"); + OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry(); + // Entry Environment ID holds actually the environment NAME + opEnvEntry.setEnvironmentId(notificationData.getOperationalEnvironmentId()); + opEnvEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS); + opEnvEntry.setIsProduction(false); + saveOpEnvEntry(errorWrapper, opEnvEntry); + opEnvEntryWrapper.setInnerElement(opEnvEntry); + + } + + + void validateState(Wrapper errorWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - verify OperationalEnvironment not In-Progress"); + String opEnvId = notificationData.getOperationalEnvironmentId(); + + Either eitherOpEnv = operationalEnvironmentDao + .get(opEnvId); + if (eitherOpEnv.isLeft()) { + final OperationalEnvironmentEntry opEnvEntry = eitherOpEnv.left().value(); + if (StringUtils.equals(opEnvEntry.getStatus(), EnvironmentStatusEnum.IN_PROGRESS.getName())) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate State Failed Record Found With Status : {} Flow Stopped!", opEnvEntry.getStatus()); + } + } else { + CassandraOperationStatus operationStatus = eitherOpEnv.right().value(); + if (operationStatus != CassandraOperationStatus.NOT_FOUND) { + errorWrapper.setInnerElement(false); + log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId, + operationStatus); + } + } + + } + + void validateActionType(Wrapper errorWrapper, IDmaapNotificationData notificationData) { + log.debug("handle message - verify Action Type"); + DmaapActionEnum action = notificationData.getAction(); + if (action == DmaapActionEnum.DELETE) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate Action Type Failed With Action Type: {} Flow Stopped!", action); + } + } + + void validateEnvironmentType(Wrapper errorWrapper, IDmaapNotificationData notificationData, + IDmaapAuditNotificationData auditNotificationData) { + log.debug("handle message - verify OperationaEnvironmentType"); + OperationaEnvironmentTypeEnum envType = notificationData.getOperationalEnvironmentType(); + if (envType != OperationaEnvironmentTypeEnum.ECOMP) { + errorWrapper.setInnerElement(false); + log.debug("handle message - validate Environment Type Failed With Environment Type: {} Flow Stopped!", envType); + componentUtils.auditEnvironmentEngine(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE, + notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(), + notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(), + auditNotificationData.getTenantContext()); + } + } + + + private void saveOpEnvEntry(Wrapper errorWrapper, OperationalEnvironmentEntry entry) { + entry.setLastModified(new Date(System.currentTimeMillis())); + CassandraOperationStatus saveStaus = operationalEnvironmentDao.save(entry); + if (saveStaus != CassandraOperationStatus.OK) { + errorWrapper.setInnerElement(false); + log.debug("handle message saving operational environmet failed for id :{} with error : {}", + entry.getEnvironmentId(), saveStaus); + } + } + + public List discoverUebHosts(String opEnvKey, String env) throws DME2Exception { + DmeConfiguration dmeConfiguration = configurationManager.getConfiguration().getDmeConfiguration(); + List uebHosts = new LinkedList<>(); + + String lookupURI = String.format("http://%s/service=%s/version=1.0.0/envContext=%s/partner=*", dmeConfiguration.getDme2Search(), opEnvKey, + env); + DME2EndpointIterator iterator = epIterCreator.create(lookupURI); + + // Beginning iteration + while (iterator.hasNext()) { + DME2EndpointReference ref = iterator.next(); + DME2Endpoint dmeEndpoint = ref.getEndpoint(); + log.debug("DME returns EP with UEB host {}, UEB port: {}", dmeEndpoint.getHost(), dmeEndpoint.getPort()); + uebHosts.add(dmeEndpoint.getHost()); + } + + return uebHosts; + } + + private String map2OpEnvKey(OperationalEnvironmentEntry entry) { + return String.format("%s.%s.%s", entry.getTenant(), entry.getEcompWorkloadContext(), MESSAGE_BUS); + } + + private Map populateEnvironments() { + Map envs = getEnvironmentsFromDb(); + OperationalEnvironmentEntry confEntry = readEnvFromConfig(); + envs.put(confEntry.getEnvironmentId(), confEntry); + return envs; + } + + private OperationalEnvironmentEntry readEnvFromConfig() { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + DistributionEngineConfiguration distributionEngineConfiguration = configurationManager + .getDistributionEngineConfiguration(); + entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey()); + entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey()); + + Set puebEndpoints = new HashSet<>(); + puebEndpoints.addAll(distributionEngineConfiguration.getUebServers()); + entry.setDmaapUebAddress(puebEndpoints); + + String envName = distributionEngineConfiguration.getEnvironments().size() == 1 + ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN; + entry.setEnvironmentId(envName); + + if(log.isDebugEnabled()) { + log.debug("Enviroment read from configuration: {}", entry.toString()); + } + + return entry; + } + + private Map getEnvironmentsFromDb() { + Either, CassandraOperationStatus> opEnvResult = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); + + if (opEnvResult.isLeft()) { + Map resultMap = opEnvResult.left().value().stream() + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + resultMap.forEach( (key, value) -> log.debug("Enviroment loaded from DB: {}", value.toString()) ); + return resultMap; + } else { + CassandraOperationStatus status = opEnvResult.right().value(); + log.debug("Failed to populate Operation Envirenments Map from Cassandra, DB status: {}", status); + return new HashMap<>(); + } + } + + void createUebTopicsForEnvironments() { + environments.values().forEach(this::createUebTopicsForEnvironment); + } + + public void createUebTopicsForEnvironment(OperationalEnvironmentEntry opEnvEntry) { + String envId = opEnvEntry.getEnvironmentId(); + log.debug("Create Environment {} on UEB Topic.", envId); + AtomicBoolean status = new AtomicBoolean(false); + envNamePerStatus.put(envId, status); + + connectUebTopicTenantIsolation(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask); + } + + @VisibleForTesting + void setConfigurationManager(ConfigurationManager configurationManager) { + this.configurationManager = configurationManager; + } + + public Map getEnvironments() { + return environments; + } + + + public Either getOperationalEnvById(String id) { + HttpResponse resp = aaiRequestHandler.getOperationalEnvById(id); + if (resp.getStatusCode() == HttpStatus.SC_OK) { + try { + OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(resp.getResponse()); + + log.debug("Get \"{}\" operational environment. {}", id, operationalEnvInfo); + return Either.left(operationalEnvInfo); + } catch (Exception e) { + log.debug("Json convert to OperationalEnvInfo failed with exception ", e); + return Either.right(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } else { + log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id, + resp.getStatusCode(), resp.getDescription()); + return Either.right(resp.getStatusCode()); + } + } + + public OperationalEnvironmentEntry getEnvironmentById (String envId) { + return environments.get(envId); + } + + public boolean isInMap(OperationalEnvironmentEntry env) { + return isInMap(env.getEnvironmentId()); + } + + public boolean isInMap(String envId) { + return environments.containsKey(envId); + } + + public void addToMap(OperationalEnvironmentEntry opEnvEntry) { + environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry); + + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java new file mode 100644 index 0000000000..29579c64b7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +@Component("executorFactory") +/** + * Allows to create next kinds of single thread executors: SingleThreadExecutor and SingleThreadScheduledExecutor + */ +public class ExecutorFactory { + + private static final Logger logger = LoggerFactory.getLogger(EnvironmentsEngine.class); + + public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler){ + logger.info("Going to create single thread executor. "); + ThreadFactory threadFactory = createThreadFactory(name, exceptionHandler); + return Executors.newSingleThreadExecutor(threadFactory); + } + + public ScheduledExecutorService createScheduled(String name){ + logger.info("Going to create single thread scheduled executor. "); + ThreadFactory threadFactory = createThreadFactory(name, + (t, e) -> LoggerFactory.getLogger(UncaughtExceptionHandler.class).error("An error occurred: ", e)); + return Executors.newSingleThreadScheduledExecutor(threadFactory); + } + + private ThreadFactory createThreadFactory(String name, UncaughtExceptionHandler exceptionHandler) { + String nameFormat = name + "-%d"; + return new ThreadFactoryBuilder() + .setThreadFactory(Executors.defaultThreadFactory()) + .setNameFormat(nameFormat) + .setUncaughtExceptionHandler(exceptionHandler) + .setDaemon(true) + .build(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java index 169f4f3efa..4a917710a9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java @@ -24,40 +24,40 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; public interface IArtifactInfo { - /** Artifact File name */ - String getArtifactName(); - - /** - * Artifact Type.
- * Following are valid values : HEAT , DG_XML.
- * List of values will be extended in post-1510 releases. - */ - ArtifactTypeEnum getArtifactType(); - - /** - * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.
- * The full artifact URL will be in the following format :
- * https://{serverBaseURL}/{resourcePath}
- * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port
- * resourcePath - "artifactURL"
- * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml - */ - String getArtifactURL(); - - /** - * Base-64 encoded MD5 checksum of the artifact's payload.
- * Should be used for data integrity validation when an artifact's payload is downloaded.
- */ - String getArtifactChecksum(); - - /** - * Installation timeout. Used by the orchestrator. - */ - Integer getArtifactTimeout(); - - /** - * Artifact description - */ - String getArtifactDescription(); + /** Artifact File name */ + String getArtifactName(); + + /** + * Artifact Type.
+ * Following are valid values : HEAT , DG_XML.
+ * List of values will be extended in post-1510 releases. + */ + ArtifactTypeEnum getArtifactType(); + + /** + * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.
+ * The full artifact URL will be in the following format :
+ * https://{serverBaseURL}/{resourcePath}
+ * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port
+ * resourcePath - "artifactURL"
+ * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml + */ + String getArtifactURL(); + + /** + * Base-64 encoded MD5 checksum of the artifact's payload.
+ * Should be used for data integrity validation when an artifact's payload is downloaded.
+ */ + String getArtifactChecksum(); + + /** + * Installation timeout. Used by the orchestrator. + */ + Integer getArtifactTimeout(); + + /** + * Artifact description + */ + String getArtifactDescription(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java index a27156616b..96abfe087c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,26 +20,35 @@ package org.openecomp.sdc.be.components.distribution.engine; +import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import fj.data.Either; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; public interface IDistributionEngine { - public boolean isActive(); + boolean isActive(); + + ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName); + + ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName); + + StorageOperationStatus isEnvironmentAvailable(String envName); + + StorageOperationStatus isEnvironmentAvailable(); - public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName); + /** + * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task. + * + * @param envName + */ + void disableEnvironment(String envName); - public StorageOperationStatus isEnvironmentAvailable(String envName); + StorageOperationStatus isReadyForDistribution(Service service, String envName); - /** - * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task. - * - * @param envName - */ - public void disableEnvironment(String envName); + INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext); - public Either isReadyForDistribution(Service service, String distributionId, String envName); + StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service); + OperationalEnvironmentEntry getEnvironmentById(String opEnvId); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java new file mode 100644 index 0000000000..c1b7a313fb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +public interface IDmaapAuditNotificationData { + String getOperationalEnvironmentName(); + String getTenantContext(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java new file mode 100644 index 0000000000..7b974e8a96 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.distribution.engine; + +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.getEnumValueByFieldValue; + +public interface IDmaapNotificationData { + String getOperationalEnvironmentId(); + + OperationaEnvironmentTypeEnum getOperationalEnvironmentType(); + + DmaapActionEnum getAction(); + + + + + + enum DmaapActionEnum { + DELETE("Delete"), + CREATE("Create"), + UPDATE("Update"), + UNKONW("UNKONW") + + ; + private String actionName; + + private DmaapActionEnum(String actionName) { + this.actionName = actionName; + } + + public String getActionName() { + return actionName; + } + + public static DmaapActionEnum findByName(String actionName){ + return getEnumValueByFieldValue(actionName, DmaapActionEnum.values(), DmaapActionEnum::getActionName, UNKONW, false); + } + }; + enum OperationaEnvironmentTypeEnum { + ECOMP("ECOMP"), + UNKONW("UNKONW") + ; + private String eventTypenName; + + private OperationaEnvironmentTypeEnum(String eventTypenName) { + this.eventTypenName = eventTypenName; + } + + public String getEventTypenName() { + return eventTypenName; + } + + public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName){ + return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(), OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false); + } + }; + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java index d631724701..d66f8f92f1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java @@ -23,84 +23,84 @@ package org.openecomp.sdc.be.components.distribution.engine; import java.util.List; public interface INotificationData { - /** - * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.
- * Generated UUID is compliant with RFC 4122.
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getDistributionID(); - - /** Logical Service Name. */ - String getServiceName(); - - /** - * Service Version.
- * Two dot (".") separated digit blocks.
- * Ex. : "2.0" - */ - String getServiceVersion(); - - /** - * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getServiceUUID(); - - /** - * Service description - */ - String getServiceDescription(); - - /** - * ServiceInvariant UUID - */ - String getServiceInvariantUUID(); - - /** List of the resource instances */ - List getResources(); - - /** List of the artifacts */ - List getServiceArtifacts(); - - String getWorkloadContext(); - - void setDistributionID(String distributionId); - - /** Logical Service Name. */ - void setServiceName(String serviceName); - - /** - * Service Version.
- * Two dot (".") separated digit blocks.
- * Ex. : "2.0" - */ - void setServiceVersion(String serviceVersion); - - /** - * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 - */ - void setServiceUUID(String serviceUUID); - - /** - * Service Description - */ - void setServiceDescription(String serviceDescription); - - /** - * ServiceInvariant UUID - */ - void setServiceInvariantUUID(String serviceInvariantUuid); - - /** List of the Resource Instances */ - void setResources(List resource); - - /** List of the Resource Instances */ - void setServiceArtifacts(List artifacts); - - void setWorkloadContext(String workloadContext); + /** + * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.
+ * Generated UUID is compliant with RFC 4122.
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getDistributionID(); + + /** Logical Service Name. */ + String getServiceName(); + + /** + * Service Version.
+ * Two dot (".") separated digit blocks.
+ * Ex. : "2.0" + */ + String getServiceVersion(); + + /** + * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getServiceUUID(); + + /** + * Service description + */ + String getServiceDescription(); + + /** + * ServiceInvariant UUID + */ + String getServiceInvariantUUID(); + + /** List of the resource instances */ + List getResources(); + + /** List of the artifacts */ + List getServiceArtifacts(); + + String getWorkloadContext(); + + void setDistributionID(String distributionId); + + /** Logical Service Name. */ + void setServiceName(String serviceName); + + /** + * Service Version.
+ * Two dot (".") separated digit blocks.
+ * Ex. : "2.0" + */ + void setServiceVersion(String serviceVersion); + + /** + * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ * Ex. : AA97B177-9383-4934-8543-0F91A7A02836 + */ + void setServiceUUID(String serviceUUID); + + /** + * Service Description + */ + void setServiceDescription(String serviceDescription); + + /** + * ServiceInvariant UUID + */ + void setServiceInvariantUUID(String serviceInvariantUuid); + + /** List of the Resource Instances */ + void setResources(List resource); + + /** List of the Resource Instances */ + void setServiceArtifacts(List artifacts); + + void setWorkloadContext(String workloadContext); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java new file mode 100644 index 0000000000..a1936c61dd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +public interface INotificationHandler { + /** + * Allows to handle received topic message + * @param notification + * @return true if finished successfully otherwise false + */ + public boolean handleMessage(String notification); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java index 9a77b9f94f..deac8751b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java @@ -22,18 +22,18 @@ package org.openecomp.sdc.be.components.distribution.engine; public interface IResourceArtifactInfo extends IArtifactInfo { - /** resource name */ - String getResourceName(); + /** resource name */ + String getResourceName(); - /** resource version */ - String getResourceVersion(); + /** resource version */ + String getResourceVersion(); - /** - * Global UUID of the resource that specific artifact belongs to.
- * It is generated by ASDC per each resource version.
- * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
- * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 - */ - String getResourceUUID(); + /** + * Global UUID of the resource that specific artifact belongs to.
+ * It is generated by ASDC per each resource version.
+ * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836 + */ + String getResourceUUID(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java index 5efcfe7fa8..db0e1e938d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java @@ -20,109 +20,129 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.List; - import org.openecomp.sdc.be.model.ComponentInstance; +import java.util.List; + public class JsonContainerResourceInstance { - private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory; - private List artifacts; - - public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List artifacts) { - super(); - this.resourceInstanceName = resourceInstance.getName(); - this.resourceName = resourceInstance.getComponentName(); - this.resourceVersion = resourceInstance.getComponentVersion(); - this.resoucreType = resourceType; - this.resourceUUID = resourceInstance.getComponentUid(); - this.artifacts = artifacts; - this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); - } - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResoucreType() { - return resoucreType; - } - - public void setResoucreType(String resoucreType) { - this.resoucreType = resoucreType; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - public String getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(String resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceCustomizationUUID() { - return resourceCustomizationUUID; - } - - public void setResourceCustomizationUUID(String customizationUUID) { - this.resourceCustomizationUUID = customizationUUID; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } - - @Override - public String toString() { - return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID - + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; - } - + private String resourceInstanceName; + private String resourceName; + private String resourceVersion; + private String resourceType; + private String resourceUUID; + private String resourceInvariantUUID; + private String resourceCustomizationUUID; + private String category; + private String subcategory; + private List artifacts; + + public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List artifacts) { + super(); + this.resourceInstanceName = resourceInstance.getName(); + this.resourceName = resourceInstance.getComponentName(); + this.resourceVersion = resourceInstance.getComponentVersion(); + this.resourceType = resourceType; + this.resourceUUID = resourceInstance.getComponentUid(); + this.artifacts = artifacts; + this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); + } + + public JsonContainerResourceInstance(ComponentInstance resourceInstance, List artifacts) { + super(); + this.resourceInstanceName = resourceInstance.getName(); + this.resourceName = resourceInstance.getComponentName(); + this.resourceVersion = resourceInstance.getComponentVersion(); + if(resourceInstance.getOriginType() != null) + this.resourceType = resourceInstance.getOriginType().getValue(); + this.resourceUUID = resourceInstance.getComponentUid(); + this.artifacts = artifacts; + this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID(); + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resourceType; + } + + public void setResoucreType(String resoucreType) { + this.resourceType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceCustomizationUUID() { + return resourceCustomizationUUID; + } + + public void setResourceCustomizationUUID(String customizationUUID) { + this.resourceCustomizationUUID = customizationUUID; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + @Override + public String toString() { + return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resourceType + ", resourceUUID=" + resourceUUID + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java index 353039647d..1db67a9581 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java @@ -24,111 +24,111 @@ import java.util.List; public class NotificationDataImpl implements INotificationData { - private String distributionID; - private String serviceName; - private String serviceVersion; - private String serviceUUID; - private String serviceDescription; - private String serviceInvariantUUID; - private List resources; - private List serviceArtifacts; - private String workloadContext; - - @Override - public String getDistributionID() { - return distributionID; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public String getServiceVersion() { - return serviceVersion; - } - - @Override - public String getServiceUUID() { - return serviceUUID; - } - - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public void setServiceVersion(String serviceVersion) { - this.serviceVersion = serviceVersion; - } - - public void setServiceUUID(String serviceUUID) { - this.serviceUUID = serviceUUID; - } - - public String getServiceDescription() { - return serviceDescription; - } - - public void setServiceDescription(String serviceDescription) { - this.serviceDescription = serviceDescription; - } - @Override - public String getWorkloadContext() { return workloadContext; } - - @Override - public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } - - @Override - public String toString() { - return "NotificationDataImpl{" + - "distributionID='" + distributionID + '\'' + - ", serviceName='" + serviceName + '\'' + - ", serviceVersion='" + serviceVersion + '\'' + - ", serviceUUID='" + serviceUUID + '\'' + - ", serviceDescription='" + serviceDescription + '\'' + - ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + - ", resources=" + resources + - ", serviceArtifacts=" + serviceArtifacts + - ", workloadContext='" + workloadContext + '\'' + - '}'; - } - - @Override - public List getResources() { - return resources; - } - - @Override - public void setResources(List resources) { - this.resources = resources; - - } - - @Override - public List getServiceArtifacts() { - // TODO Auto-generated method stub - return serviceArtifacts; - } - - @Override - public void setServiceArtifacts(List serviceArtifacts) { - this.serviceArtifacts = serviceArtifacts; - - } - - @Override - public String getServiceInvariantUUID() { - return serviceInvariantUUID; - } - - @Override - public void setServiceInvariantUUID(String serviceInvariantUUID) { - this.serviceInvariantUUID = serviceInvariantUUID; - } + private String distributionID; + private String serviceName; + private String serviceVersion; + private String serviceUUID; + private String serviceDescription; + private String serviceInvariantUUID; + private List resources; + private List serviceArtifacts; + private String workloadContext; + + @Override + public String getDistributionID() { + return distributionID; + } + + @Override + public String getServiceName() { + return serviceName; + } + + @Override + public String getServiceVersion() { + return serviceVersion; + } + + @Override + public String getServiceUUID() { + return serviceUUID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + @Override + public String getWorkloadContext() { return workloadContext; } + + @Override + public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } + + @Override + public String toString() { + return "NotificationDataImpl{" + + "distributionID='" + distributionID + '\'' + + ", serviceName='" + serviceName + '\'' + + ", serviceVersion='" + serviceVersion + '\'' + + ", serviceUUID='" + serviceUUID + '\'' + + ", serviceDescription='" + serviceDescription + '\'' + + ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + + ", resources=" + resources + + ", serviceArtifacts=" + serviceArtifacts + + ", workloadContext='" + workloadContext + '\'' + + '}'; + } + + @Override + public List getResources() { + return resources; + } + + @Override + public void setResources(List resources) { + this.resources = resources; + + } + + @Override + public List getServiceArtifacts() { + // TODO Auto-generated method stub + return serviceArtifacts; + } + + @Override + public void setServiceArtifacts(List serviceArtifacts) { + this.serviceArtifacts = serviceArtifacts; + + } + + @Override + public String getServiceInvariantUUID() { + return serviceInvariantUUID; + } + + @Override + public void setServiceInvariantUUID(String serviceInvariantUUID) { + this.serviceInvariantUUID = serviceInvariantUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java index 74fbb2c660..dc58a24e5f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java @@ -20,62 +20,57 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - +import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.util.concurrent.*; public class NotificationExecutorService { - private static Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class); - public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) { + public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) { - Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize(); - if (minThreadPoolSize == null) { - minThreadPoolSize = 0; - } + Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize(); + if (minThreadPoolSize == null) { + minThreadPoolSize = 0; + } - Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize(); - if (maxThreadPoolSize == null) { - maxThreadPoolSize = 10; - } + Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize(); + if (maxThreadPoolSize == null) { + maxThreadPoolSize = 10; + } - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d"); - ThreadFactory threadFactory = threadFactoryBuilder.build(); + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d"); + ThreadFactory threadFactory = threadFactoryBuilder.build(); - ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue(), threadFactory); + ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue(), threadFactory); - return executorService; - } + return executorService; + } - public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) { + public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) { - logger.debug("shutdown NotificationExecutorService"); - pool.shutdown(); // Disable new tasks from being submitted - try { - // Wait a while for existing tasks to terminate - if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { - pool.shutdownNow(); // Cancel currently executing tasks - // Wait a while for tasks to respond to being cancelled - if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { - logger.debug("Failed to close executor service"); - } - } - } catch (InterruptedException ie) { - // (Re-)Cancel if current thread also interrupted - pool.shutdownNow(); - // Preserve interrupt status - Thread.currentThread().interrupt(); - } - } + logger.debug("shutdown NotificationExecutorService"); + pool.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { + pool.shutdownNow(); // Cancel currently executing tasks + // Wait a while for tasks to respond to being cancelled + if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) { + logger.debug("Failed to close executor service"); + } + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + pool.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java deleted file mode 100644 index c283ecc92b..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java +++ /dev/null @@ -1,156 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.distribution.engine; - -import org.openecomp.sdc.be.config.DistributionEngineConfiguration; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PublishNotificationRunnable implements Runnable { - - private String envName; - private String distributionId; - private Service service; - private INotificationData data; - private DistributionEngineConfiguration deConfiguration; - private String topicName; - private CambriaHandler cambriaHandler; - private ComponentsUtils componentUtils; - private String userId; - private String modifierName; - private String requestId; - - private static Logger logger = LoggerFactory.getLogger(PublishNotificationRunnable.class.getName()); - - public PublishNotificationRunnable(String envName, String distributionId, Service service, INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName, String userId, String modifierName, - CambriaHandler cambriaHandler, ComponentsUtils componentUtils, String requestId) { - super(); - this.envName = envName; - this.distributionId = distributionId; - this.service = service; - this.data = data; - this.deConfiguration = deConfiguration; - this.topicName = topicName; - this.cambriaHandler = cambriaHandler; - this.componentUtils = componentUtils; - this.userId = userId; - this.modifierName = modifierName; - this.requestId = requestId; - } - - public INotificationData getData() { - return data; - } - - public void setData(INotificationData data) { - this.data = data; - } - - public DistributionEngineConfiguration getDeConfiguration() { - return deConfiguration; - } - - public void setDeConfiguration(DistributionEngineConfiguration deConfiguration) { - this.deConfiguration = deConfiguration; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getModifierName() { - return modifierName; - } - - public void setModifierName(String modifierName) { - this.modifierName = modifierName; - } - - @Override - public void run() { - - long startTime = System.currentTimeMillis(); - ThreadLocalsHolder.setUuid(this.requestId); - - CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data, - deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds()); - - logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode()); - auditDistributionNotification(topicName, status, service, distributionId, envName, userId, modifierName); - - long endTime = System.currentTimeMillis(); - logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime)); - - } - - private void auditDistributionNotification(String topicName, CambriaErrorResponse status, Service service, String distributionId, String envName, String userId, String modifierName) { - if (this.componentUtils != null) { - Integer httpCode = status.getHttpCode(); - String httpCodeStr = String.valueOf(httpCode); - - String desc = getDescriptionFromErrorResponse(status); - - this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envName, service.getLifecycleState().name(), topicName, - distributionId, desc, httpCodeStr); - } - } - - private String getDescriptionFromErrorResponse(CambriaErrorResponse status) { - - CambriaOperationStatus operationStatus = status.getOperationStatus(); - - switch (operationStatus) { - case OK: - return "OK"; - case AUTHENTICATION_ERROR: - return "Error: Authentication problem towards U-EB server"; - case INTERNAL_SERVER_ERROR: - return "Error: Internal U-EB server error"; - case UNKNOWN_HOST_ERROR: - return "Error: Cannot reach U-EB server host"; - case CONNNECTION_ERROR: - return "Error: Cannot connect to U-EB server"; - case OBJECT_NOT_FOUND: - return "Error: object not found in U-EB server"; - default: - return "Error: Internal Cambria server problem"; - - } - - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java index 31f3cb6fda..19a857a115 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java @@ -22,37 +22,37 @@ package org.openecomp.sdc.be.components.distribution.engine; public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResourceArtifactInfo { - private String resourceName; - private String resourceVersion; - private String resourceUUID; - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - @Override - public String toString() { - return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]"; - } + private String resourceName; + private String resourceVersion; + private String resourceUUID; + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + @Override + public String toString() { + return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java index 50d1700f37..1d626805f6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java @@ -22,9 +22,9 @@ package org.openecomp.sdc.be.components.distribution.engine; public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServiceArtifactInfo { - @Override - public String toString() { - return "ServiceArtifactInfoImpl [" + super.toString() + "]"; - } + @Override + public String toString() { + return "ServiceArtifactInfoImpl [" + super.toString() + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java index 0330a756c6..f3d17979ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java @@ -20,26 +20,16 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.slf4j.Logger; @@ -47,279 +37,224 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; +import java.util.stream.Collectors; @Component("serviceDistributionArtifactsBuilder") public class ServiceDistributionArtifactsBuilder { - private int defaultArtifactInstallTimeout = 60; - - private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName()); - - final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; - final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s"; - final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; - - final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; - - @javax.annotation.Resource - InterfaceLifecycleOperation interfaceLifecycleOperation; - - @javax.annotation.Resource - IArtifactOperation artifactOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - /* - * @javax.annotation.Resource private - * InformationDeployedArtifactsBusinessLogic - * informationDeployedArtifactsBusinessLogic; - */ - - @PostConstruct - private void init() { - defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration() - .getDefaultHeatArtifactTimeoutMinutes(); - } - - public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { - return interfaceLifecycleOperation; - } - - public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { - this.interfaceLifecycleOperation = interfaceLifecycleOperation; - } - - public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId) { - INotificationData notificationData = new NotificationDataImpl(); - - notificationData.setResources(convertRIToJsonContanier(service)); - notificationData.setServiceName(service.getName()); - notificationData.setServiceVersion(service.getVersion()); - notificationData.setDistributionID(distributionId); - notificationData.setServiceUUID(service.getUUID()); - notificationData.setServiceDescription(service.getDescription()); - notificationData.setServiceInvariantUUID(service.getInvariantUUID()); - String workloadContext= ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); - if(workloadContext!=null){ - notificationData.setWorkloadContext(workloadContext); - } - logger.debug("Before returning notification data object {}", notificationData); - - return notificationData; - - } - - public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) { - - notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service)); - - logger.debug("Before returning notification data object {}", notificationData); - - return notificationData; - - } - - private List convertServiceArtifactsToArtifactInfo(Service service) { - - Map serviceArtifactsMap = service.getDeploymentArtifacts(); - List extractedServiceArtifacts = serviceArtifactsMap.values().stream() - //filters all artifacts with existing EsId - .filter(artifactDef -> artifactDef.checkEsIdExist()) - //collects all filtered artifacts with existing EsId to List - .collect(Collectors.toList()); - - Optional toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service); - if(toscaTemplateArtifactOptl.isPresent()){ - extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); - } - - Optional toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); - if(toscaCsarArtifactOptl.isPresent()){ - extractedServiceArtifacts.add(toscaCsarArtifactOptl.get()); - } - - List artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts); - return artifacts; - } - - private Optional exrtactToscaTemplateArtifact(Service service) { - return service.getToscaArtifacts().values().stream() - //filters TOSCA_TEMPLATE artifact - .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny(); - } - - private Optional exrtactToscaCsarArtifact(Service service) { - return service.getToscaArtifacts().values().stream() - //filters TOSCA_CSAR artifact - .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny(); - } - - private List convertRIToJsonContanier(Service service) { - List ret = new ArrayList(); - if (service.getComponentInstances() != null) { - for (ComponentInstance resourceInstance : service.getComponentInstances()) { - String resoucreType = resourceInstance.getOriginType().getValue(); - List artifactsDefList = getArtifactsWithPayload(resourceInstance); - List artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, - artifactsDefList); - - String resourceInvariantUUID = null; - String resourceCategory = null; - String resourceSubcategory = null; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - Either componentResponse = toscaOperationFacade - .getToscaElement(resourceInstance.getComponentUid(), componentParametersView); - - if (componentResponse.isRight()) { - logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid()); - } else { - Resource resource = componentResponse.left().value(); - resourceInvariantUUID = resource.getInvariantUUID(); - - List categories = resource.getCategories(); - - if (categories != null) { - CategoryDefinition categoryDefinition = categories.get(0); - - if (categoryDefinition != null) { - resourceCategory = categoryDefinition.getName(); - List subcategories = categoryDefinition.getSubcategories(); - if (null != subcategories) { - SubCategoryDefinition subCategoryDefinition = subcategories.get(0); - - if (subCategoryDefinition != null) { - resourceSubcategory = subCategoryDefinition.getName(); - } - } - } - } - } - - JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType, - rebuildArtifactswith120TimeoutInsteadOf60(artifacts)/*TODO used to send artifacts, the function is a fix to the short timeout bug in distribution*/); - jsonContainer.setResourceInvariantUUID(resourceInvariantUUID); - jsonContainer.setCategory(resourceCategory); - jsonContainer.setSubcategory(resourceSubcategory); - ret.add(jsonContainer); - } - } - return ret; - } - - private List rebuildArtifactswith120TimeoutInsteadOf60(List artifacts) { - for(ArtifactInfoImpl artifact : artifacts){ - if(artifact.getArtifactTimeout().equals(60)){ - artifact.setArtifactTimeout(120); - } - } - return artifacts; - } - - private List getArtifactsWithPayload(ComponentInstance resourceInstance) { - List ret = new ArrayList(); - - // List informationDeployedArtifacts = - // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance); - List deployableArtifacts = new ArrayList(); - // deployableArtifacts.addAll(informationDeployedArtifacts); - if (resourceInstance.getDeploymentArtifacts() != null) { - deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values()); - } - - for (ArtifactDefinition artifactDef : deployableArtifacts) { - if (artifactDef.checkEsIdExist()) { - ret.add(artifactDef); - } - } - - return ret; - } - - /** - * build the url for resource intance artifact - * - * @param service - * @param resourceData - * @param artifactName - * @return - */ - public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, - String artifactName) { - - String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), - resourceInstance.getNormalizedName(), artifactName); - - logger.debug("After building artifact url {}", url); - - return url; - } - - /** - * build the url for resource intance artifact - * - * @param service - * @param resourceData - * @param artifactName - * @return - */ - public static String buildServiceArtifactUrl(Service service, String artifactName) { - - String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName); - - logger.debug("After building artifact url {}", url); - - return url; - - } - - /** - * Retrieve all deployment artifacts of all resources under a given service - * - * @param resourceArtifactsResult - * @param service - * @param deConfiguration - * @return - */ - public Either isServiceContainsDeploymentArtifacts(Service service) { - - Either result = Either.left(false); - Map serviseArtifactsMap = service.getDeploymentArtifacts(); - if (serviseArtifactsMap != null && !serviseArtifactsMap.isEmpty()) { - result = Either.left(true); - return result; - } - - List resourceInstances = service.getComponentInstances(); - - if (resourceInstances != null) { - for (ComponentInstance resourceInstance : resourceInstances) { - - Map deploymentArtifactsMapper = resourceInstance.getDeploymentArtifacts(); - // List informationDeployedArtifacts = - // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance); - - boolean isDeployableArtifactFound = isContainsPayload(deploymentArtifactsMapper.values());// || - // isContainsPayload(informationDeployedArtifacts); - if (isDeployableArtifactFound) { - result = Either.left(true); - break; - } - - } - - } - - return result; - } - - private boolean isContainsPayload(Collection collection) { - boolean payLoadFound = collection != null && collection.stream().anyMatch(p -> p.checkEsIdExist()); - return payLoadFound; - } + private static final Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class); + + static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/"; + static final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s"; + static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s"; + static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s"; + + @javax.annotation.Resource + InterfaceLifecycleOperation interfaceLifecycleOperation; + + @javax.annotation.Resource + IArtifactOperation artifactOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + public InterfaceLifecycleOperation getInterfaceLifecycleOperation() { + return interfaceLifecycleOperation; + } + + public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { + this.interfaceLifecycleOperation = interfaceLifecycleOperation; + } + + private String resolveWorkloadContext(String workloadContext) { + return workloadContext != null ? workloadContext : + ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext(); + } + + public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) { + INotificationData notificationData = new NotificationDataImpl(); + + notificationData.setResources(convertRIsToJsonContanier(service)); + notificationData.setServiceName(service.getName()); + notificationData.setServiceVersion(service.getVersion()); + notificationData.setDistributionID(distributionId); + notificationData.setServiceUUID(service.getUUID()); + notificationData.setServiceDescription(service.getDescription()); + notificationData.setServiceInvariantUUID(service.getInvariantUUID()); + workloadContext = resolveWorkloadContext(workloadContext); + if (workloadContext!=null){ + notificationData.setWorkloadContext(workloadContext); + } + logger.debug("Before returning notification data object {}", notificationData); + + return notificationData; + } + + public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) { + + notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service)); + + logger.debug("Before returning notification data object {}", notificationData); + + return notificationData; + } + + private List convertServiceArtifactsToArtifactInfo(Service service) { + + Map serviceArtifactsMap = service.getDeploymentArtifacts(); + List extractedServiceArtifacts = serviceArtifactsMap.values().stream() + //filters all artifacts with existing EsId + .filter(ArtifactDefinition::checkEsIdExist) + //collects all filtered artifacts with existing EsId to List + .collect(Collectors.toList()); + + Optional toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service); + if(toscaTemplateArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get()); + } + + Optional toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service); + if(toscaCsarArtifactOptl.isPresent()){ + extractedServiceArtifacts.add(toscaCsarArtifactOptl.get()); + } + + return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts); + } + + private Optional exrtactToscaTemplateArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_TEMPLATE artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny(); + } + + private Optional exrtactToscaCsarArtifact(Service service) { + return service.getToscaArtifacts().values().stream() + //filters TOSCA_CSAR artifact + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny(); + } + + private List convertRIsToJsonContanier(Service service) { + List ret = new ArrayList<>(); + if (service.getComponentInstances() != null) { + for (ComponentInstance instance : service.getComponentInstances()) { + JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance)); + ComponentParametersView filter = new ComponentParametersView(); + filter.disableAll(); + filter.setIgnoreCategories(false); + toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter) + .left() + .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);}) + .right() + .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid())); + ret.add(jsonContainer); + } + } + return ret; + } + + private void fillJsonContainer(JsonContainerResourceInstance jsonContainer, Resource resource) { + jsonContainer.setResourceInvariantUUID(resource.getInvariantUUID()); + setCategories(jsonContainer, resource.getCategories()); + } + + private List convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) { + List artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance)); + artifacts.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout); + return artifacts; + } + + private void setCategories(JsonContainerResourceInstance jsonContainer, List categories) { + if (categories != null) { + CategoryDefinition categoryDefinition = categories.get(0); + + if (categoryDefinition != null) { + jsonContainer.setCategory(categoryDefinition.getName()); + List subcategories = categoryDefinition.getSubcategories(); + if (null != subcategories) { + SubCategoryDefinition subCategoryDefinition = subcategories.get(0); + + if (subCategoryDefinition != null) { + jsonContainer.setSubcategory(subCategoryDefinition.getName()); + } + } + } + } + } + + private List getArtifactsWithPayload(ComponentInstance resourceInstance) { + List ret = new ArrayList<>(); + + List deployableArtifacts = new ArrayList<>(); + if (resourceInstance.getDeploymentArtifacts() != null) { + deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values()); + } + + for (ArtifactDefinition artifactDef : deployableArtifacts) { + if (artifactDef.checkEsIdExist()) { + ret.add(artifactDef); + } + } + + return ret; + } + + /** + * build the URL for resource instance artifact + * + * @param service + * @param resourceInstance + * @param artifactName + * @return URL string + */ + public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, + String artifactName) { + + String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), + resourceInstance.getNormalizedName(), artifactName); + + logger.debug("After building artifact url {}", url); + + return url; + } + + /** + * build the URL for resource instance artifact + * + * @param service + * @param artifactName + * @return URL string + */ + public static String buildServiceArtifactUrl(Service service, String artifactName) { + + String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName); + + logger.debug("After building artifact url {}", url); + + return url; + + } + + /** + * Verifies that the service or at least one of its instance contains deployment artifacts + * + * @param the service + * @return boolean + */ + public boolean verifyServiceContainsDeploymentArtifacts(Service service) { + if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) { + return true; + } + boolean contains = false; + List resourceInstances = service.getComponentInstances(); + if (CollectionUtils.isNotEmpty(resourceInstances)) { + contains = resourceInstances.stream().anyMatch(i -> isContainsPayload(i.getDeploymentArtifacts())); + } + return contains; + } + + private boolean isContainsPayload(Map deploymentArtifacts) { + return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java index f8c0e3f593..3477648dbd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine; public enum SubscriberTypeEnum { - CONSUMER, PRODUCER; + CONSUMER, PRODUCER; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java index c522ca91b5..7a25c2ed69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java @@ -20,58 +20,58 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.concurrent.Callable; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.Callable; + public class UebHealthCheckCall implements Callable { - CambriaHandler cambriaHandler = new CambriaHandler(); + CambriaHandler cambriaHandler = new CambriaHandler(); - String server; - String publicApiKey; + String server; + String publicApiKey; - private static Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); + private static final Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT); - private static Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class); - public UebHealthCheckCall(String server, String publicApiKey) { - super(); - this.server = server; - this.publicApiKey = publicApiKey; - } + public UebHealthCheckCall(String server, String publicApiKey) { + super(); + this.server = server; + this.publicApiKey = publicApiKey; + } - @Override - public Boolean call() { + @Override + public Boolean call() { - healthLogger.trace("Going to run health check towards ueb server {}", server); + healthLogger.trace("Going to run health check towards ueb server {}", server); - boolean result = false; - CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey); + boolean result = false; + CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey); - logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse); + logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse); - if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) { - logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode); - result = true; - } + if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) { + logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode); + result = true; + } - healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result); + healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result); - return result; - } + return result; + } - public String getServer() { - return server; - } + public String getServer() { + return server; + } - public CambriaHandler getCambriaHandler() { - return cambriaHandler; - } + public CambriaHandler getCambriaHandler() { + return cambriaHandler; + } - public void setCambriaHandler(CambriaHandler cambriaHandler) { - this.cambriaHandler = cambriaHandler; - } + public void setCambriaHandler(CambriaHandler cambriaHandler) { + this.cambriaHandler = cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java index d706e40f5c..8f0865f2ac 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java @@ -20,105 +20,100 @@ package org.openecomp.sdc.be.components.distribution.engine; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.common.api.Constants; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + public class VfModuleArtifactPayload { - - private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; - private Boolean isBase; - private List artifacts; - private Map< String, Object> properties; - - public VfModuleArtifactPayload(GroupDefinition group) { - vfModuleModelName = group.getName(); - vfModuleModelInvariantUUID = group.getInvariantUUID(); - vfModuleModelVersion = group.getVersion(); - vfModuleModelUUID = group.getGroupUUID(); - vfModuleModelDescription = group.getDescription(); - - artifacts = group.getArtifactsUuid(); - // Base Value is set from properties - setBaseValue(group); - - } - - public VfModuleArtifactPayload(GroupInstance group) { - vfModuleModelName = group.getGroupName(); - vfModuleModelInvariantUUID = group.getInvariantUUID(); - vfModuleModelVersion = group.getVersion(); - vfModuleModelUUID = group.getGroupUUID(); - vfModuleModelCustomizationUUID = group.getCustomizationUUID(); - vfModuleModelDescription = group.getDescription(); - - artifacts = group.getArtifactsUuid(); - artifacts.addAll(group.getGroupInstanceArtifactsUuid()); - - // Base Value is set from properties - setBaseValue(group); - - if(group.convertToGroupInstancesProperties() != null) - setProperties(group.convertToGroupInstancesProperties()); - //converts List of GroupInstanceProperties to Map propertyName : GroupInstanceProperty () - //setProperties(group.getGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p))); - - } - - private void setBaseValue(GroupInstance group) { - if (group.convertToGroupInstancesProperties() != null) { - Optional findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (findBaseProperty.isPresent()) { - isBase = Boolean.valueOf(findBaseProperty.get().getValue()); - } - - } - } - private void setBaseValue(GroupDefinition group) { - if (group.getProperties() != null) { - Optional findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (findBaseProperty.isPresent()) { - isBase = Boolean.valueOf(findBaseProperty.get().getValue()); - } - - } - } - - - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - - - public Map getProperties() { - return properties; - } - - /*public void setProperties(Map properties) { - this.properties = properties; - }*/ - - public void setProperties(List properties) { - this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect( - Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() )); - } - - public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) { - Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); - Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); - return thisCounter.compareTo(otherCounter); - } + + private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription; + private Boolean isBase; + private List artifacts; + private Map< String, Object> properties; + + public VfModuleArtifactPayload(GroupDefinition group) { + vfModuleModelName = group.getName(); + vfModuleModelInvariantUUID = group.getInvariantUUID(); + vfModuleModelVersion = group.getVersion(); + vfModuleModelUUID = group.getGroupUUID(); + vfModuleModelDescription = group.getDescription(); + + artifacts = group.getArtifactsUuid(); + // Base Value is set from properties + setBaseValue(group); + + } + + public VfModuleArtifactPayload(GroupInstance group) { + vfModuleModelName = group.getGroupName(); + vfModuleModelInvariantUUID = group.getInvariantUUID(); + vfModuleModelVersion = group.getVersion(); + vfModuleModelUUID = group.getGroupUUID(); + vfModuleModelCustomizationUUID = group.getCustomizationUUID(); + vfModuleModelDescription = group.getDescription(); + + artifacts = new ArrayList<>(group.getArtifactsUuid()); + artifacts.addAll(group.getGroupInstanceArtifactsUuid()); + + // Base Value is set from properties + setBaseValue(group); + + if(group.convertToGroupInstancesProperties() != null) + setProperties(group.convertToGroupInstancesProperties()); + } + + private void setBaseValue(GroupInstance group) { + if (group.convertToGroupInstancesProperties() != null) { + Optional findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (findBaseProperty.isPresent()) { + isBase = Boolean.valueOf(findBaseProperty.get().getValue()); + } + + } + } + private void setBaseValue(GroupDefinition group) { + if (group.getProperties() != null) { + Optional findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (findBaseProperty.isPresent()) { + isBase = Boolean.valueOf(findBaseProperty.get().getValue()); + } + + } + } + + + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + + + public Map getProperties() { + return properties; + } + + + public void setProperties(List properties) { + this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect( + Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() )); + } + + public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) { + Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); + Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.')); + return thisCounter.compareTo(otherCounter); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java new file mode 100644 index 0000000000..e6f2cc634f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.distribution.engine.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan({"org.openecomp.sdc.be.components.distribution.engine", + }) +public class DistributionEngineSpringConfig { + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java new file mode 100644 index 0000000000..7f9dd45e67 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.be.components.distribution.engine.report; + +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification; + +public interface DistributionCompleteReporter { + + void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java new file mode 100644 index 0000000000..4e06b0ed0e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.components.distribution.engine.report; + +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification; +import org.openecomp.sdc.be.components.distribution.engine.rest.MSORestClient; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +@Component +public class MsoDistributionCompleteReporter implements DistributionCompleteReporter { + + @Resource + private MSORestClient msoClient; + + @Override + public void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification) { + msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(), distributionStatusNotification.getErrorReason()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java new file mode 100644 index 0000000000..45727fb28f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +/** + * a class which represents an MSO distribution status rest request body + */ +public class DistributionStatusRequest { + + private String status; + private String errorReason; + + public DistributionStatusRequest(String status, String errorReason) { + this.status = status; + this.errorReason = errorReason; + } + + public String getStatus() { + return status; + } + + public String getErrorReason() { + return errorReason; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java new file mode 100644 index 0000000000..76263f942d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java @@ -0,0 +1,69 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.eclipse.jetty.util.URIUtil; +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.*; +import org.openecomp.sdc.common.http.config.BasicAuthorization; +import org.openecomp.sdc.common.http.config.ExternalServiceConfig; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.Properties; + +@Component +public class MSORestClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(MSORestClient.class); + private static final Gson gson = new Gson(); + @VisibleForTesting + static final String DISTRIBUTIONS_RESOURCE_CONFIG_PARAM = "distributions"; + + private ExternalServiceConfig serviceConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig(); + + public MSORestClient() { + HttpClientConfig httpClientConfig = serviceConfig.getHttpClientConfig(); + int numOfRetries = httpClientConfig.getNumOfRetries(); + if ( numOfRetries > 0 ) { + httpClientConfig.setRetryHandler(RetryHandlers.getDefault(numOfRetries)); + } + } + + public HttpResponse notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) { + try { + return doNotifyDistributionComplete(distributionId, distributionStatusEnum, errReason); + } + catch(HttpExecuteException e) { + LOGGER.debug("The request to mso failed with exception ", e); + return Responses.INTERNAL_SERVER_ERROR; + } + } + + private HttpResponse doNotifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) throws HttpExecuteException { + StringEntity entity = new StringEntity(gson.toJson(new DistributionStatusRequest(distributionStatusEnum.name(), errReason)), ContentType.APPLICATION_JSON); + HttpResponse response = HttpRequest.patch(buildMsoDistributionUrl(distributionId), buildReqHeader(), entity, serviceConfig.getHttpClientConfig()); + LOGGER.info("response from mso - status code: {}, status description: {}, response: {}, ", response.getStatusCode(), response.getDescription(), response.getResponse()); + return response; + } + + private Properties buildReqHeader() { + Properties properties = new Properties(); + BasicAuthorization basicAuth = serviceConfig.getHttpClientConfig().getBasicAuthorization(); + RestUtils.addBasicAuthHeader(properties, basicAuth.getUserName(), basicAuth.getPassword()); + return properties; + } + + private String buildMsoDistributionUrl(String distributionId) { + String msoBaseUrl = serviceConfig.getHttpRequestConfig().getServerRootUrl(); + String distributionsPath = serviceConfig.getHttpRequestConfig().getResourceNamespaces().get(DISTRIBUTIONS_RESOURCE_CONFIG_PARAM); + String distributionsApiPath = distributionsPath + URIUtil.SLASH + distributionId; + return msoBaseUrl + distributionsApiPath; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java new file mode 100644 index 0000000000..670350a733 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java @@ -0,0 +1,475 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.health; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; +import org.openecomp.sdc.be.components.distribution.engine.DmaapHealth; +import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; +import org.openecomp.sdc.be.components.impl.CassandraHealthCheck; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.impl.EsHealthCheckDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.HttpClientConfig; +import org.openecomp.sdc.common.http.config.Timeouts; +import org.openecomp.sdc.common.util.HealthCheckUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.stream.Collectors; + +import static java.lang.String.format; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; +import static org.apache.http.HttpStatus.SC_OK; +import static org.openecomp.sdc.common.api.Constants.*; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN; +import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP; +import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion; + + +@Component("healthCheckBusinessLogic") +public class HealthCheckBusinessLogic { + + protected static final String BE_HEALTH_LOG_CONTEXT = "be.healthcheck"; + private static final String BE_HEALTH_CHECK_STR = "beHealthCheck"; + private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s"; + private static final Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT); + private static final Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName()); + private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil(); + ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task")); + HealthCheckScheduledTask healthCheckScheduledTask = null; + @Resource + private TitanGenericDao titanGenericDao; + @Resource + private EsHealthCheckDao esHealthCheckDao; + @Resource + private DistributionEngineClusterHealth distributionEngineClusterHealth; + @Resource + private DmaapHealth dmaapHealth; + @Resource + private CassandraHealthCheck cassandraHealthCheck; + @Autowired + private SwitchoverDetector switchoverDetector; + private volatile List prevBeHealthCheckInfos = null; + private ScheduledFuture scheduledFuture = null; + + @PostConstruct + public void init() { + + prevBeHealthCheckInfos = getBeHealthCheckInfos(); + + log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos); + + healthCheckScheduledTask = new HealthCheckScheduledTask(); + + if (this.scheduledFuture == null) { + this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, SECONDS); + } + + } + + public boolean isDistributionEngineUp() { + + HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); + return !healthCheckInfo.getHealthCheckStatus().equals(DOWN); + } + + public Pair> getBeHealthCheckInfosStatus() { + Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); + return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos); + } + + private List getBeHealthCheckInfos() { + + log.trace("In getBeHealthCheckInfos"); + + List healthCheckInfos = new ArrayList<>(); + + //Dmaap + getDmaapHealthCheck(healthCheckInfos); + // BE + getBeHealthCheck(healthCheckInfos); + + // Titan + getTitanHealthCheck(healthCheckInfos); + // ES + getEsHealthCheck(healthCheckInfos); + + // Distribution Engine + getDistributionEngineCheck(healthCheckInfos); + + //Cassandra + getCassandraHealthCheck(healthCheckInfos); + + // Amdocs + getAmdocsHealthCheck(healthCheckInfos); + + //DCAE + getDcaeHealthCheck(healthCheckInfos); + + return healthCheckInfos; + } + + private List getEsHealthCheck(List healthCheckInfos) { + + // ES health check and version + String appVersion = getAppVersion(); + HealthCheckStatus healthCheckStatus; + String description; + + try { + healthCheckStatus = esHealthCheckDao.getClusterHealthStatus(); + } catch (Exception e) { + healthCheckStatus = DOWN; + description = "ES cluster error: " + e.getMessage(); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description)); + return healthCheckInfos; + } + if (healthCheckStatus.equals(DOWN)) { + description = "ES cluster is down"; + } else { + description = "OK"; + } + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description)); + return healthCheckInfos; + } + + private List getBeHealthCheck(List healthCheckInfos) { + String appVersion = getAppVersion(); + String description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, appVersion, description)); + return healthCheckInfos; + } + + private List getDmaapHealthCheck(List healthCheckInfos) { + String appVersion = getAppVersion(); + dmaapHealth.getHealthCheckInfo().setVersion(appVersion); + healthCheckInfos.add(dmaapHealth.getHealthCheckInfo()); + return healthCheckInfos; + } + + + public List getTitanHealthCheck(List healthCheckInfos) { + // Titan health check and version + String description; + boolean isTitanUp; + + try { + isTitanUp = titanGenericDao.isGraphOpen(); + } catch (Exception e) { + description = "Titan error: " + e.getMessage(); + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + return healthCheckInfos; + } + if (isTitanUp) { + description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description)); + } else { + description = "Titan graph is down"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description)); + } + return healthCheckInfos; + } + + private List getCassandraHealthCheck(List healthCheckInfos) { + + String description; + boolean isCassandraUp; + + try { + isCassandraUp = cassandraHealthCheck.getCassandraStatus(); + } catch (Exception e) { + isCassandraUp = false; + log.debug("Cassandra error: " + e.getMessage()); + } + if (isCassandraUp) { + description = "OK"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UP, null, description)); + } else { + description = "Cassandra is down"; + healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, description)); + } + return healthCheckInfos; + + } + + private void getDistributionEngineCheck(List healthCheckInfos) { + + HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); + + healthCheckInfos.add(healthCheckInfo); + + } + + private List getAmdocsHealthCheck(List healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private List getDcaeHealthCheck(List healthCheckInfos) { + HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl()); + healthCheckInfos.add(beHealthCheckInfo); + return healthCheckInfos; + } + + private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) { + HealthCheckStatus healthCheckStatus; + String description; + String version = null; + List componentsInfo = new ArrayList<>(); + final int timeout = 3000; + + if (healthCheckUrl != null) { + try { + HttpResponse httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout))); + int statusCode = httpResponse.getStatusCode(); + String aggDescription = ""; + + if (statusCode == SC_OK || statusCode == SC_INTERNAL_SERVER_ERROR) { + String response = httpResponse.getResponse(); + log.trace("{} Health Check response: {}", componentName, response); + ObjectMapper mapper = new ObjectMapper(); + Map healthCheckMap = mapper.readValue(response, new TypeReference>() { + }); + version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null; + if (healthCheckMap.containsKey("componentsInfo")) { + componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference>() { + }); + } + + if (!componentsInfo.isEmpty()) { + aggDescription = healthCheckUtil.getAggregateDescription(componentsInfo, null); + } else { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null)); + } + } else { + log.trace("{} Health Check Response code: {}", componentName, statusCode); + } + + if (statusCode != SC_OK) { + healthCheckStatus = DOWN; + description = aggDescription.length() > 0 + ? aggDescription + : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN. + if (componentsInfo.isEmpty()) { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + } else { + healthCheckStatus = UP; + description = "OK"; + } + + } catch (Exception e) { + log.error("{} unexpected response: ", componentName, e); + healthCheckStatus = DOWN; + description = componentName + " unexpected response: " + e.getMessage(); + if (componentsInfo != null && componentsInfo.isEmpty()) { + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + } + } else { + healthCheckStatus = DOWN; + description = componentName + " health check Configuration is missing"; + componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description)); + } + + return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo); + } + + @PreDestroy + protected void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (healthCheckScheduler != null) { + healthCheckScheduler.shutdown(); + } + + } + + private void logAlarm(String componentChangedMsg) { + BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg); + } + + public String getSiteMode() { + return switchoverDetector.getSiteMode(); + } + + public boolean anyStatusChanged(List beHealthCheckInfos, List prevBeHealthCheckInfos) { + + boolean result = false; + + if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) { + + Map currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus)); + Map prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus)); + + if (currentValues != null && prevValues != null) { + int currentSize = currentValues.size(); + int prevSize = prevValues.size(); + + if (currentSize != prevSize) { + + result = true; //extra/missing component + + Map notPresent = null; + if (currentValues.keySet().containsAll(prevValues.keySet())) { + notPresent = new HashMap<>(currentValues); + notPresent.keySet().removeAll(prevValues.keySet()); + } else { + notPresent = new HashMap<>(prevValues); + notPresent.keySet().removeAll(currentValues.keySet()); + } + + for (String component : notPresent.keySet()) { + logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component))); + } + + } else { + + for (Entry entry : currentValues.entrySet()) { + String key = entry.getKey(); + HealthCheckStatus value = entry.getValue(); + + if (!prevValues.containsKey(key)) { + result = true; //component missing + logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); + break; + } + + HealthCheckStatus prevHealthCheckStatus = prevValues.get(key); + + if (value != prevHealthCheckStatus) { + result = true; //component status changed + logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); + break; + } + } + } + } + + } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) { + result = false; + } else { + logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null")); + result = true; + } + + return result; + } + + private String buildOnBoardingHealthCheckUrl() { + + Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); + + if (onboardingConfig != null) { + String protocol = onboardingConfig.getProtocol(); + String host = onboardingConfig.getHost(); + Integer port = onboardingConfig.getPort(); + String uri = onboardingConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } + + log.error("onboarding health check configuration is missing."); + return null; + } + + private String buildDcaeHealthCheckUrl() { + + Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae(); + + if (dcaeConfig != null) { + String protocol = dcaeConfig.getProtocol(); + String host = dcaeConfig.getHost(); + Integer port = dcaeConfig.getPort(); + String uri = dcaeConfig.getHealthCheckUri(); + + return protocol + "://" + host + ":" + port + uri; + } + + log.error("dcae health check configuration is missing."); + return null; + } + + public class HealthCheckScheduledTask implements Runnable { + + List healthCheckCalls = new ArrayList<>(); + + @Override + public void run() { + Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration(); + healthLogger.trace("Executing BE Health Check Task"); + + List currentBeHealthCheckInfos = getBeHealthCheckInfos(); + boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude()); + + boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()); + + boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos); + + if (prevHealthStatus != healthStatus || anyStatusChanged) { + log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); + + prevBeHealthCheckInfos = currentBeHealthCheckInfos; + logAlarm(healthStatus); + } + + } + + private void logAlarm(boolean prevHealthState) { + if (prevHealthState) { + BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR); + } else { + BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR); + } + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java new file mode 100644 index 0000000000..e0a8533052 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.model.Service; + +/** + * Created by chaya on 10/22/2017. + */ +public class ActivationRequestInformation { + private Service serviceToActivate; + private String workloadContext; + private String tenant; + + public ActivationRequestInformation(Service serviceToActivate, String workloadContext, String tenant) { + this.serviceToActivate = serviceToActivate; + this.workloadContext = workloadContext; + this.tenant = tenant; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(String tenant) { + this.tenant = tenant; + } + + public Service getServiceToActivate() { + return serviceToActivate; + } + + public void setServiceToActivate(Service serviceToActivate) { + this.serviceToActivate = serviceToActivate; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java index 51b5679ffa..50331a71d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -52,514 +49,506 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.List; @Component("additionalInformationBusinessLogic") public class AdditionalInformationBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation"; - - private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation"; - - private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation"; - - private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation"; - - private static Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class.getName()); - - @javax.annotation.Resource - private IAdditionalInformationOperation additionalInformationOperation = null; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - protected static IElementOperation getElementDao(Class class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - /** - * Create new additional information on resource/service on graph - * - * @param resourceId - * @param propertyName - * @param newPropertyDefinition - * @param userId - * @return Either - */ - public Either createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either resp = validateUserExists(userId, "create Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, CREATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - try { - responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // validate label - responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - // validate value - responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - Either addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(), - additionalInfoParameterInfo.getValue(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, CREATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label)); - return result; - - } else { - AdditionalInformationDefinition informationDefinition = addResult.left().value(); - - AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); - result = Either.left(createdAI); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * Validate the value format. Format the value. - * - * @param additionalInfoParameterInfo - * @return null in case of success. Otherwise response format. - */ - private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { - ResponseFormat result = null; - - String value = additionalInfoParameterInfo.getValue(); - log.debug("Going to validate additional information value {}", value); - - Either valueValidRes = validateValue(value); - if (valueValidRes.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); - BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); - result = valueValidRes.right().value(); - } else { - String newValue = valueValidRes.left().value(); - if (log.isTraceEnabled()) { - if (value != null && false == value.equals(newValue)) { - log.trace("The additional information value was normalized from {} to {}", value, newValue); - } - } - additionalInfoParameterInfo.setValue(newValue); - } - return result; - } - - /** - * @param additionalInfoParameterInfo - * @return - */ - private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { - - String key = additionalInfoParameterInfo.getKey(); - log.debug("Going to validate additional information key {}", key); - - ResponseFormat result = null; - ResponseFormat responseFormat; - Either validateKeyRes = validateAndNormalizeKey(key); - if (validateKeyRes.isRight()) { - responseFormat = validateKeyRes.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); - BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); - result = responseFormat; - - } else { - String convertedKey = validateKeyRes.left().value(); - - if (log.isTraceEnabled()) { - if (key != null && false == key.equals(convertedKey)) { - log.trace("The additional information key {} was normalized to {}", key, convertedKey); - } - } - additionalInfoParameterInfo.setKey(convertedKey); - } - return result; - } - - /** - * verify that the maximal number of additional information properties has not been reached. - * - * @param nodeType - * @param componentId - * @param additionalInfoParameterInfo - * @return response format in case the maximal number has been reached. - */ - private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) { - - ResponseFormat result; - Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys(); - - Either checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true); - if (checkRes.isRight()) { - StorageOperationStatus status = checkRes.right().value(); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); - return result; - } - Integer currentNumberOfProperties = checkRes.left().value(); - if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) { - log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties); - result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); - return result; - } - - return null; - } - - /** - * validate additional information value - * - * @param value - * @return - */ - private Either validateValue(String value) { - - boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value); - if (false == isNonEmptyString) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED)); - } - - boolean valid = StringValidator.getInstance().isValid(value, null); - if (false == valid) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value)); - } - - String converted = StringConvertor.getInstance().convert(value, null, null); - - return Either.left(converted); - } - - private AdditionalInfoParameterInfo findAdditionInformationKey(List parameters, String key) { - - for (AdditionalInfoParameterInfo infoParameterInfo : parameters) { - if (infoParameterInfo.getKey().equals(key)) { - return infoParameterInfo; - } - } - return null; - } - - /** - * validate and normalize the key - * - * @param additionalInfoParameterInfo - * @return - */ - private Either validateAndNormalizeKey(String key) { - - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setKey(key); - - key = ValidationUtils.normalizeAdditionalInformation(key); - boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key); - if (false == isNonEmptyString) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label)); - } - boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key); - if (false == isValidString) { - if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) { - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); - } - return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); - } - - return Either.left(key); - } - - /** - * update key and value of a given additional information. - * - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * - Future use - * @param userId - * @return - */ - public Either updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either resp = validateUserExists(userId, "create Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, UPDATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - try { - - // validate input - responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); - if (responseFormat != null) { - result = Either.right(responseFormat); - return result; - } - - Either addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), - additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, UPDATE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } else { - AdditionalInformationDefinition informationDefinition = addResult.left().value(); - AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); - result = Either.left(parameterInfo); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * Delete an additional information label - * - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * - Null. Future use. - * @param userId - * @return - */ - public Either deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either resp = validateUserExists(userId, "delete Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either result = null; - - ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); - if (responseFormat != null) { - return Either.right(responseFormat); - } - // lock component - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, DELETE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); - log.info("Failed to lock component {} error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - - Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - if (findIdRes.isRight()) { - StorageOperationStatus status = findIdRes.right().value(); - if (status != StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, GET_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION); - } - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } - - AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); - - Either addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - - if (addResult.isRight()) { - StorageOperationStatus status = addResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, DELETE_ADDITIONAL_INFORMATION); - BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - return result; - } else { - result = Either.left(foundAdditionalInfo); - return result; - } - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, nodeType); - } - - } - - /** - * @param nodeType - * @param resourceId - * @param additionalInfoParameterInfo - * @param additionalInformationUid - * @param userId - * @return - */ - public Either getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { - - Either resp = validateUserExists(userId, "get Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either result = null; - - try { - - Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); - - if (findIdRes.isRight()) { - StorageOperationStatus status = findIdRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); - } - - AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); - - result = Either.left(foundAdditionalInfo); - - return result; - - } finally { - commitOrRollback(result); - } - - } - - /** - * Get all additional information properties of a given resource/service - * - * @param nodeType - * @param resourceId - * @param additionalInformationUid - * - Future use - * @param userId - * @return - */ - public Either getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) { - - Either resp = validateUserExists(userId, "get All Additional Information", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either result = null; - - try { - - Either findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); - if (findIdRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value()); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); - result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus)); - } else { - AdditionalInformationDefinition informationDefinition = findIdRes.left().value(); - result = Either.left(informationDefinition); - } - - return result; - - } finally { - commitOrRollback(result); - } - - } - - private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) { - - switch (nodeType) { - case Resource: - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { - return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } - break; - case Service: - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { - return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } - break; - default: - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName()); - } - - return null; - } + private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation"; + + private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation"; + + private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation"; + + private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation"; + + private static final Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class); + + @javax.annotation.Resource + private IAdditionalInformationOperation additionalInformationOperation = null; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + protected static IElementOperation getElementDao(Class class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + /** + * Create new additional information on resource/service on graph + * + * @param resourceId + * @param propertyName + * @param newPropertyDefinition + * @param userId + * @return Either + */ + public Either createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either resp = validateUserExists(userId, "create Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + try { + responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // validate label + responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + // validate value + responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + Either addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(), + additionalInfoParameterInfo.getValue(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label)); + return result; + + } else { + AdditionalInformationDefinition informationDefinition = addResult.left().value(); + + AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); + result = Either.left(createdAI); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * Validate the value format. Format the value. + * + * @param additionalInfoParameterInfo + * @return null in case of success. Otherwise response format. + */ + private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { + ResponseFormat result = null; + + String value = additionalInfoParameterInfo.getValue(); + log.debug("Going to validate additional information value {}", value); + + Either valueValidRes = validateValue(value); + if (valueValidRes.isRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string"); + result = valueValidRes.right().value(); + } else { + String newValue = valueValidRes.left().value(); + if (log.isTraceEnabled()) { + if (value != null && false == value.equals(newValue)) { + log.trace("The additional information value was normalized from {} to {}", value, newValue); + } + } + additionalInfoParameterInfo.setValue(newValue); + } + return result; + } + + /** + * @param additionalInfoParameterInfo + * @return + */ + private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) { + + String key = additionalInfoParameterInfo.getKey(); + log.debug("Going to validate additional information key {}", key); + + ResponseFormat result = null; + ResponseFormat responseFormat; + Either validateKeyRes = validateAndNormalizeKey(key); + if (validateKeyRes.isRight()) { + responseFormat = validateKeyRes.right().value(); + BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string"); + result = responseFormat; + + } else { + String convertedKey = validateKeyRes.left().value(); + + if (log.isTraceEnabled()) { + if (key != null && false == key.equals(convertedKey)) { + log.trace("The additional information key {} was normalized to {}", key, convertedKey); + } + } + additionalInfoParameterInfo.setKey(convertedKey); + } + return result; + } + + /** + * verify that the maximal number of additional information properties has not been reached. + * + * @param nodeType + * @param componentId + * @param additionalInfoParameterInfo + * @return response format in case the maximal number has been reached. + */ + private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) { + + ResponseFormat result; + Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys(); + + Either checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true); + if (checkRes.isRight()) { + StorageOperationStatus status = checkRes.right().value(); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); + return result; + } + Integer currentNumberOfProperties = checkRes.left().value(); + if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) { + log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties); + result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None); + return result; + } + + return null; + } + + /** + * validate additional information value + * + * @param value + * @return + */ + private Either validateValue(String value) { + + boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value); + if (false == isNonEmptyString) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED)); + } + + boolean valid = StringValidator.getInstance().isValid(value, null); + if (false == valid) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value)); + } + + String converted = StringConvertor.getInstance().convert(value, null, null); + + return Either.left(converted); + } + + private AdditionalInfoParameterInfo findAdditionInformationKey(List parameters, String key) { + + for (AdditionalInfoParameterInfo infoParameterInfo : parameters) { + if (infoParameterInfo.getKey().equals(key)) { + return infoParameterInfo; + } + } + return null; + } + + /** + * validate and normalize the key + * + * @param additionalInfoParameterInfo + * @return + */ + private Either validateAndNormalizeKey(String key) { + + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setKey(key); + + key = ValidationUtils.normalizeAdditionalInformation(key); + boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key); + if (false == isNonEmptyString) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label)); + } + boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key); + if (false == isValidString) { + if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) { + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); + } + return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label)); + } + + return Either.left(key); + } + + /** + * update key and value of a given additional information. + * + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * - Future use + * @param userId + * @return + */ + public Either updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either resp = validateUserExists(userId, "create Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + try { + + // validate input + responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION); + if (responseFormat != null) { + result = Either.right(responseFormat); + return result; + } + + Either addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), + additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } else { + AdditionalInformationDefinition informationDefinition = addResult.left().value(); + AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey()); + result = Either.left(parameterInfo); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * Delete an additional information label + * + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * - Null. Future use. + * @param userId + * @return + */ + public Either deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either resp = validateUserExists(userId, "delete Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either result = null; + + ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId); + if (responseFormat != null) { + return Either.right(responseFormat); + } + // lock component + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId); + log.info("Failed to lock component {} error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + + Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + if (findIdRes.isRight()) { + StorageOperationStatus status = findIdRes.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION); + } + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } + + AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); + + Either addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + + if (addResult.isRight()) { + StorageOperationStatus status = addResult.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + return result; + } else { + result = Either.left(foundAdditionalInfo); + return result; + } + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, nodeType); + } + + } + + /** + * @param nodeType + * @param resourceId + * @param additionalInfoParameterInfo + * @param additionalInformationUid + * @param userId + * @return + */ + public Either getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) { + + Either resp = validateUserExists(userId, "get Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either result = null; + + try { + + Either findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true); + + if (findIdRes.isRight()) { + StorageOperationStatus status = findIdRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None)); + } + + AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value(); + + result = Either.left(foundAdditionalInfo); + + return result; + + } finally { + commitOrRollback(result); + } + + } + + /** + * Get all additional information properties of a given resource/service + * + * @param nodeType + * @param resourceId + * @param additionalInformationUid + * - Future use + * @param userId + * @return + */ + public Either getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) { + + Either resp = validateUserExists(userId, "get All Additional Information", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either result = null; + + try { + + Either findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false); + if (findIdRes.isRight()) { + StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status); + result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus)); + } else { + AdditionalInformationDefinition informationDefinition = findIdRes.left().value(); + result = Either.left(informationDefinition); + } + + return result; + + } finally { + commitOrRollback(result); + } + + } + + private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) { + + switch (nodeType) { + case Resource: + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { + return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + break; + case Service: + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) { + return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + break; + default: + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName()); + } + + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java index 1c5a35453b..fcaf5cdfc6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,6 +29,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Service; +import java.util.*; @org.springframework.stereotype.Component("artifact-resolver") public class ArtifactResolverImpl implements ArtifactsResolver { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index bd7f61444d..39ad806cda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,25 +20,10 @@ package org.openecomp.sdc.be.components.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; - +import com.google.common.annotations.VisibleForTesting; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; @@ -60,25 +45,12 @@ import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ArtifactType; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; @@ -92,6 +64,7 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.servlets.RepresentationUtils; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.ToscaError; @@ -119,4953 +92,5363 @@ import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.yaml.snakeyaml.Yaml; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - +import javax.servlet.http.HttpServletRequest; +import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - -import fj.data.Either; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("artifactBusinessLogic") public class ArtifactsBusinessLogic extends BaseBusinessLogic { - private static final String ARTIFACT_TYPE_OTHER = "OTHER"; - private static final String ARTIFACT_DESCRIPTION = "artifact description"; - private static final String ARTIFACT_LABEL = "artifact label"; - private static final String ARTIFACT_URL = "artifact url"; - private static final String ARTIFACT_NAME = "artifact name"; - private static final String ARTIFACT_PAYLOAD = "artifact payload"; - - private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; - private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; - private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - - public static final String HEAT_ENV_NAME = "heatEnv"; - public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; - public static final String HEAT_ENV_SUFFIX = "env"; - private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; - - // private static Integer defaultHeatTimeout; - // private static final Integer NON_HEAT_TIMEOUT = 0; - private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static XMLReader parser; - @javax.annotation.Resource - private IInterfaceLifecycleOperation interfaceLifecycleOperation; - @javax.annotation.Resource - private IUserAdminOperation userOperaton; - - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - @javax.annotation.Resource - private UserBusinessLogic userAdminManager; - - @javax.annotation.Resource - private IHeatParametersOperation heatParametersOperation; - - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - - @Autowired - private ToscaExportHandler toscaExportUtils; - - @Autowired - private CsarUtils csarUtils; - - @Autowired - private LifecycleBusinessLogic lifecycleBusinessLogic; - - @Autowired - private IUserBusinessLogic userBusinessLogic; - @Autowired - NodeTemplateOperation nodeTemplateOperation; - - @Autowired - private ArtifactsResolver artifactsResolver; - - public ArtifactsBusinessLogic() { - // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { - // defaultHeatTimeout = 60; - // } - } - - public static enum ArtifactOperationEnum { - Create(), Update(), Delete(), Download(), Link(); - - public static boolean isCreateOrLink(ArtifactOperationEnum operation) { - return (operation.equals(Create) || operation.equals(Link)); - - } - } - - //SAX XML Parser initialization - static { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser newSAXParser = null; - - try { - newSAXParser = spf.newSAXParser(); - parser = newSAXParser.getXMLReader(); - } catch (ParserConfigurationException | SAXException e1) { - log.debug("SAX XML Parser could not been initialized", e1); - } - - try { - parser.setFeature("http://apache.org/xml/features/validation/schema", false); - } catch (SAXNotRecognizedException e) { - log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - - } catch (SAXNotSupportedException e) { - log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); - - } - } - - public class ArtifactOperationInfo { - - private ArtifactOperationEnum artifactOperationEnum; - private boolean isExternalApi; - private boolean ignoreLifecycleState; - - public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { - this.artifactOperationEnum = artifactOperationEnum; - this.isExternalApi = isExternalApi; - this.ignoreLifecycleState = ignoreLifecycleState; - } - - public boolean isExternalApi() { - return isExternalApi; - } - - public boolean ignoreLifecycleState() { - return ignoreLifecycleState; - } - - public ArtifactOperationEnum getArtifactOperationEnum() { - return artifactOperationEnum; - } - - } - - // new flow US556184 - public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { - return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); - } - - public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, - String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { - - // step 1 - detect auditing type - AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - // step 2 - check header - if (userId == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); - handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - // step 3 - check user existence - Either userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); - if (userResult.isRight()) { - return Either.right(userResult.right().value()); - } - - // step 4 - check user's role - User user = userResult.left().value(); - Either validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); - if (validateUserRole.isRight()) { - return Either.right(validateUserRole.right().value()); - } - - // steps 5 - 6 - 7 - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - // ComponentInstance resourceInstance = null; - String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - Either validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction); - if (validateComponent.isRight()) { - return Either.right(validateComponent.right().value()); - } - component = validateComponent.left().value(); - Either validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType); - if (validateWorkOnResource.isRight()) { - return Either.right(validateWorkOnResource.right().value()); - } - // step 8 - Either, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component, - shouldLock, inTransaction, true); - - return result; - } - - /** - * This Method validates only the Artifact and does not validate user / role / component ect...
- * For regular usage use
- * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)} - * - * @return - */ - public Either, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, - ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - Component parent = component; - Wrapper errorWrapper = new Wrapper<>(); - - AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); - artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction); - - Either, ResponseFormat> result; - if (errorWrapper.isEmpty()) { - // step 10 - result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user, - org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper errorWrapper, boolean inTransaction) { - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { - Either validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction); - if (validateArtifact.isRight()) { - ResponseFormat responseFormat = validateArtifact.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - errorWrapper.setInnerElement(validateArtifact.right().value()); - } else { - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) { - artifactInfo = validateArtifact.left().value(); - handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper); - } - } - } - return artifactInfo; - } - - private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either validateArtifact, boolean shouldLock, - Wrapper errorWrapper) { - ArtifactDefinition validatedArtifact = validateArtifact.left().value(); - - if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - if (ComponentTypeEnum.SERVICE == component.getComponentType()) { - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get(); - Map deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - - ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get(); - Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId); - if (eitherGenerated.isRight()) { - errorWrapper.setInnerElement(eitherGenerated.right().value()); - } - } - } - } - - private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { - boolean needGenerate; - needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); - return needGenerate; - } - - private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) { - return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); - } - - public Either, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, - boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { - - Either, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); - if (generated.isRight()) { - return generated; - } - byte[] decodedPayload = artifactDefinition.getPayloadData(); - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload)); - return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null, - shouldLock, inTransaction); - - } - - private Either, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { - log.debug("tosca artifact generation"); - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { - Either generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); - - if (generated.isRight()) { - log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value()); - - return Either.right(generated.right().value()); - } - byte[] value = generated.left().value(); - artifactInfo.setPayload(value); - - } else { - Either exportComponent = toscaExportUtils.exportComponent(parent); - if (exportComponent.isRight()) { - log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value()); - ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status); - return Either.right(responseFormat); - } - log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); - String payload = exportComponent.left().value().getMainYaml(); - artifactInfo.setPayloadData(payload); - } - return Either.left(Either.left(artifactInfo)); - } - - private Either, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, - String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { - if (interfaceName != null && operationName != null) { - interfaceName = interfaceName.toLowerCase(); - operationName = operationName.toLowerCase(); - } - switch (operation.getArtifactOperationEnum()) { - case Download: - if (artifactGenerationRequired(parent, artifactInfo)) { - return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction); - } - return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); - case Delete: - return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction); - case Update: - Either, ResponseFormat> result = null; - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) - && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { - result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either updateResult = result.left().value(); - ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } - } - } else { - if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { - result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup); - } - } - if (result == null) { - result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - if (needUpdateGroup && result.isLeft()) { - Either updateResult = result.left().value(); - - ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType); - if (error != ActionStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(error)); - } - } - } - return result; - case Create: - return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - case Link: - return handleLink(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); - } - return null; - } - - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) { - List groups = parent.getGroups(); - if (groups != null && !groups.isEmpty()) { - List groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList()); - if (groupToUpdate != null && !groupToUpdate.isEmpty()) { - groupToUpdate.forEach(g -> { - g.getArtifacts().remove(artifactInfo.getUniqueId()); - g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID()); - g.getArtifacts().add(artAfterUpdate.getUniqueId()); - g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); - }); - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - } - } - return ActionStatus.OK; - } - - private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) { - List groups = parent.getGroups(); - if (groups != null && !groups.isEmpty()) { - List groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList()); - if (groupToUpdate != null && !groupToUpdate.isEmpty()) { - groupToUpdate.forEach(g -> { - g.getArtifacts().remove(artifactInfoHeat.getUniqueId()); - g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID()); - g.getArtifacts().remove(artifactInfoHeatE.getUniqueId()); - g.getArtifacts().add(artHeatAfterUpdate.getUniqueId()); - g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID()); - g.getArtifacts().add(artHEAfterUpdate.getUniqueId()); - }); - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - } - } - return ActionStatus.OK; - } - - private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) { - List updatedGroupInstances = new ArrayList<>(); - List groupInstances = null; - Optional componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst(); - if (componentInstOp.isPresent()) { - groupInstances = componentInstOp.get().getGroupInstances(); - } - if (CollectionUtils.isNotEmpty(groupInstances)) { - boolean isUpdated = false; - for (GroupInstance groupInstance : groupInstances) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) { - groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId()); - groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId()); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) { - groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); - groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroupInstances.add(groupInstance); - } - } - } - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); - return componentsUtils.convertFromStorageResponse(status.right().value()); - } - return ActionStatus.OK; - } - - Either, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) { - Either, ResponseFormat> result; - if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { - result = generateToscaArtifact(parent, artifactInfo, false, false); - } else { - String heatArtifactId = artifactInfo.getGeneratedFromId(); - Either heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); - if (heatRes.isRight()) { - log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), ""); - return Either.right(responseFormat); - } - String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); - artifactInfo.setPayloadData(generatedPayload); - result = Either.left(Either.left(artifactInfo)); - } - return result; - } - - private Either, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); - Either artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId()); - ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); - - if (origMd5 != null) { - Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - - Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - - // lock resource - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Update Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup); - return resultOp; - - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - if (false == inTransaction) - titanDao.rollback(); - } else { - log.debug("all changes committed"); - if (false == inTransaction) - titanDao.commit(); - } - if (shouldLock) - componentType = parent.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - } - - public Either, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { - if (artifactGenerationRequired(component, csarArtifact)) { - Either generated = csarUtils.createCsar(component, false, false); - - if (generated.isRight()) { - log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value()); - - return Either.right(generated.right().value()); - } - return Either.left(new ImmutablePair(csarArtifact.getArtifactName(), generated.left().value())); - } - return downloadArtifact(csarArtifact, component); - } - - public Either, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { - // perform all validation in common flow - Either, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null, - null, parentId, containerComponentType); - if (result.isRight()) { - return Either.right(result.right().value()); - } - ArtifactDefinition artifactDefinition; - Either insideValue = result.left().value(); - if (insideValue.isLeft()) { - artifactDefinition = insideValue.left().value(); - } else { - artifactDefinition = insideValue.right().value().getImplementationArtifact(); - } - // for tosca artifacts and heat env on VF level generated on download without saving - if (artifactDefinition.getPayloadData() != null) { - return Either.left(new ImmutablePair(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData())); - } - return downloadArtifact(artifactDefinition, null); - } - - public Either, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { - // step 1 - // detect auditing type - Map resMap = null; - Either, ResponseFormat> resultOp = null; - - new Wrapper<>(); - // step 2 - // check header - if (userId == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); - - resultOp = Either.right(responseFormat); - return resultOp; - } - // step 3 - // check user existence - // step 4 - // check user's role - - Either userResult = validateUserExists(userId, "get artifacts", false); - if (userResult.isRight()) { - - resultOp = Either.right(userResult.right().value()); - return resultOp; - } - - userResult.left().value(); - - // steps 5 - 6 - 7 - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - // ComponentInstance resourceInstance = null; - String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - ComponentParametersView componentFilter = new ComponentParametersView(); - componentFilter.disableAll(); - componentFilter.setIgnoreArtifacts(false); - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) - componentFilter.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false); - - if (validateComponent.isRight()) { - resultOp = Either.right(validateComponent.right().value()); - return resultOp; - } - component = validateComponent.left().value(); - Either lockComponent = lockComponent(component, "Update Artifact - lock "); - if (lockComponent.isRight()) { - - resultOp = Either.right(lockComponent.right().value()); - return resultOp; - } - - try { - ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); - - if (groupType == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - - resultOp = Either.right(responseFormat); - return resultOp; - - } - if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { - List list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); - if (list != null && !list.isEmpty()) { - resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); - } else { - resMap = new HashMap<>(); - } - resultOp = Either.left(resMap); - return resultOp; - } else { - - Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId); - if (artifactsMapStatus.isRight()) { - if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); - resultOp = Either.right(responseFormat); - } else { - resMap = new HashMap<>(); - resultOp = Either.left(resMap); - } - } else { - resMap = artifactsMapStatus.left().value(); - resultOp = Either.left(resMap); - } - return resultOp; - } - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - titanDao.rollback(); - } else { - log.debug("all changes committed"); - - titanDao.commit(); - } - - componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - - } - - private Either validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId, - boolean inTransaction) { - // step 9 - // check artifact existence - Either artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId()); - if (artifactResult.isRight()) { - if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - log.debug("addArtifact - artifact {} not found", artifactId); - return Either.right(responseFormat); - - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value())); - log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value()); - return Either.right(responseFormat); - } - } - // step 9.1 - // check artifact belong to component - boolean found = false; - switch (componentType) { - case RESOURCE: - case SERVICE: - found = checkArtifactInComponent(component, artifactId); - break; - case RESOURCE_INSTANCE: - found = checkArtifactInResourceInstance(component, componentId, artifactId); - break; - default: - - } - if (!found) { - // String component = - // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" : - // "service"; - String componentName = componentType.name().toLowerCase(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName); - log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId); - return Either.right(responseFormat); - } - return Either.left(artifactResult.left().value()); - } - - private Either, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - String artifactId = null; - - // step 11 - Either payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction); - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - convertParentType(componentType); - - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either, ResponseFormat> resultOp = null; - - try { - resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName); - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - - } - - } - - private Either, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either, ResponseFormat> resultOp = null; - - try { - resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - - } - - } - - private Either, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - convertParentType(componentType); - - // lock resource - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Update Artifact - lock "); - - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - - Either, ResponseFormat> resultOp = null; - try { - resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName); - return resultOp; - - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - } - } - - private Either, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, - ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - Either payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction); - - if (payloadEither.isRight()) { - return Either.right(payloadEither.right().value()); - } - byte[] decodedPayload = payloadEither.left().value(); - - return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); - } - - private Either validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) { - // Md5 validations - Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - // step 11 - Either validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction); - if (validateResult.isRight()) { - ResponseFormat responseFormat = validateResult.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(validateResult.right().value()); - } - - Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - log.debug("Error during handle payload"); - return Either.right(responseFormat); - } - - // validate heat parameters. this part must be after the parameters are - // extracted in "handlePayload" - Either validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType()); - if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); - handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); - log.debug("Error during handle payload"); - return Either.right(responseFormat); - } - return payloadEither; - } - - public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, - ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { - - if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { - return; - } - - EnumMap auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid); - - if (user == null) { - user = new User(); - user.setUserId("UNKNOWN"); - } - switch (componentTypeEnum) { - - case RESOURCE: - Resource resource = (Resource) component; - if (resource == null) { - // In that case, component ID should be instead of name - resource = new Resource(); - resource.setName(componentId); - } - componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields); - break; - - case SERVICE: - Service service = (Service) component; - if (service == null) { - // In that case, component ID should be instead of name - service = new Service(); - service.setName(componentId); - } - componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields); - break; - - case RESOURCE_INSTANCE: - if (resourceInstanceName == null) { - resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields); - - break; - default: - break; - } - } - - private String getResourceInstanceNameFromComponent(Component component, String componentId) { - ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null); - String resourceInstanceName = null; - if (resourceInstance != null) { - resourceInstanceName = resourceInstance.getName(); - } - return resourceInstanceName; - } - - public EnumMap createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) { - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - // Putting together artifact info - String artifactData = buildAuditingArtifactData(artifactDefinition); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid); - return auditingFields; - } - - // ----- - - private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) { - StringBuilder sb = new StringBuilder(); - if (artifactDefinition != null) { - sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",") - .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId()); - - sb.append(","); - if (artifactDefinition.getArtifactVersion() != null) { - - sb.append(artifactDefinition.getArtifactVersion()); - } else { - sb.append(" "); - } - sb.append(","); - if (artifactDefinition.getArtifactUUID() != null) { - sb.append(artifactDefinition.getArtifactUUID()); - } else { - sb.append(" "); - } - } - return sb.toString(); - } - - private Either validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { - - if (origMd5 != null) { - String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData); - - if (false == encodeBase64Str.equals(origMd5)) { - log.debug("The calculated md5 is different then the received one"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - } else { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - if (payload!=null && payload.length != 0) { - log.debug("Missing md5 header during artifact create"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); - } - } - // Update metadata - if (payload != null && payload.length != 0) { - log.debug("Cannot have payload while md5 header is missing"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - return Either.left(true); - } - - private Either validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, - ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) { - - Either artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); - if (artifactById.isRight()) { - return Either.right(artifactById.right().value()); - } - ArtifactDefinition currentArtifactInfo = artifactById.left().value(); - - ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo); - Either validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); - if (validateInformationalArtifactRes.isRight()) { - return Either.right(validateInformationalArtifactRes.right().value()); - } - Either validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); - if (validateAndSetArtifactname.isRight()) { - return Either.right(validateAndSetArtifactname.right().value()); - } - if (operationName != null && interfaceName != null) { - operationName = operationName.toLowerCase(); - interfaceName = interfaceName.toLowerCase(); - } - Either logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType); - if (logicalNameStatus.isRight()) { - return Either.right(logicalNameStatus.right().value()); - } - // This is a patch to block possibility of updating service api fields - // through other artifacts flow - - if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); - } else { - checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL)); - } - - composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName); - if (currentArtifactInfo != null) { - artifactInfo.setMandatory(currentArtifactInfo.getMandatory()); - } - - // artifactGroupType is not allowed to be updated - if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - Either validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); - if (validateGroupType.isRight()) { - return Either.right(validateGroupType.right().value()); - } - } - // TODO TEMP !!! - NodeTypeEnum parentType = convertParentType(componentType); - - // TODO TEMP !!! - boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); - - if (isDeploymentArtifact(artifactInfo)) { - Either deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType); - if (deploymentValidationResult.isRight()) { - return Either.right(deploymentValidationResult.right().value()); - } - } else { - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - - /* - * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo, - * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } } - */ - } - - Either descriptionResult = validateAndCleanDescription(artifactInfo); - if (descriptionResult.isRight()) { - return Either.right(descriptionResult.right().value()); - } - - if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) { - Either validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType); - if (validateServiceApiType.isRight()) { - return Either.right(validateServiceApiType.right().value()); - } - // Change of type is not allowed and should be ignored - - artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER); - - Either validateUrl = validateAndServiceApiUrl(artifactInfo); - if (validateUrl.isRight()) { - return Either.right(validateUrl.right().value()); - } - - Either validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo); - if (validateUpdate.isRight()) { - log.debug("serviceApi first update cnnot be without payload."); - return Either.right(validateUpdate.right().value()); - } - } else { - Either validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType); - if (validateArtifactType.isRight()) { - return Either.right(validateArtifactType.right().value()); - } - if (artifactInfo.getApiUrl() != null) { - artifactInfo.setApiUrl(null); - log.error("Artifact URL cannot be set through this API - ignoring"); - } - - if (artifactInfo.getServiceApi() != null) { - if (artifactInfo.getServiceApi()) { - artifactInfo.setServiceApi(false); - log.error("Artifact service API flag cannot be changed - ignoring"); - } - } - } - - return Either.left(artifactInfo); - } - - private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) { - if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){ - artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); - artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType()); - artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel()); - } - } - - private Either findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { - - Either result = null; - ArtifactDefinition foundArtifact = null; - if (StringUtils.isNotEmpty(artifactId)) { - foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); - } - if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - log.debug("Artifact {} already exist", artifactId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); - } - if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); - } - if (result == null) { - result = Either.left(foundArtifact); - } - return result; - } - - private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { - ArtifactDefinition foundArtifact; - if (parentComponent.getUniqueId().equals(parentId)) { - foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); - } else { - ComponentInstance instance = findComponentInstance(parentId, parentComponent); - foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); - } - return foundArtifact; - } - - private Either validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { - ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - Either validationResult = Either.left(true); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (artifactType == null) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { - String artifactTypeName = artifactType.getType(); - ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); - Map resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts(); - Set validArtifactTypes = resourceInformationalArtifacts.keySet(); - if (!validArtifactTypes.contains(artifactTypeName)) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); - } else { - List validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes(); - if (!validResourceType.contains(parentResourceType.name())) { - validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); - } - } - } - return validationResult; - } - - private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - return NodeTypeEnum.Resource; - } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { - return NodeTypeEnum.ResourceInstance; - } else { - return NodeTypeEnum.Service; - } - } - - public Either, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, - String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { - - NodeTypeEnum parentType = convertParentType(componentType); - Either, ResponseFormat> resultOp = null; - Either, ActionStatus> getArtifactRes = null; - ArtifactDefinition foundArtifact = null; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - Either getContainerRes = null; - org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; - boolean isDuplicated = false; - String esId = null; - Either needCloneRes = null; - try { - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - resultOp = Either.right(lockComponent.right().value()); - } - } - if (resultOp == null) { - log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); - getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - if (resultOp == null) { - fetchedContainerComponent = getContainerRes.left().value(); - log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); - getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); - if (getArtifactRes.isRight()) { - log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } else { - foundArtifact = getArtifactRes.left().value().getLeft(); - esId = foundArtifact.getEsId(); - } - } - if (resultOp == null && StringUtils.isNotEmpty(esId)) { - needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType())); - if (needCloneRes.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - boolean isNeedToDeleteArtifactFromDB = true; - if (resultOp == null) { - - if(componentType == ComponentTypeEnum.RESOURCE_INSTANCE){ - String instanceId = parentId; - Either isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); - - if (isOnlyResourceInstanceArtifact.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right().value(), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); - } - - Either updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value()); - if (updatedArtifactRes.isRight()) { - log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } else { - isDuplicated = updatedArtifactRes.left().value().getDuplicated(); - } - } - - if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) { - - if(isNeedToDeleteArtifactFromDB){ - log.debug("Going to delete the artifact {} from the database. ", artifactId); - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); - if (cassandraStatus != CassandraOperationStatus.OK) { - log.debug("Failed to delete the artifact {} from the database. ", artifactId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - - List updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances()); - if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { - List updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups()); - if (CollectionUtils.isNotEmpty(updatedGroups)) { - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); - responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName()); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - } - } - } - if (resultOp == null) { - resultOp = Either.left(Either.left(foundArtifact)); - handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); - } - return resultOp; - } finally { - if (shouldLock) { - unlockComponent(resultOp, parent, inTransaction); - } - } - } - - private Either isArtifactOnlyResourceInstanceArtifact( ArtifactDefinition foundArtifact, Component parent, String instanceId) { - Either result = Either.left(true); - ComponentInstance foundInstance = null; - Optional componentInstanceOpt = parent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if (!componentInstanceOpt.isPresent()) { - result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); - } else { - foundInstance = componentInstanceOpt.get(); - String componentUid = foundInstance.getComponentUid(); - Either getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); - if (getContainerRes.isRight()) { - log.debug("Failed to fetch the container component {}. ", componentUid); - result = Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); - } - Component origComponent = getContainerRes.left().value(); - Map deploymentArtifacts = origComponent.getDeploymentArtifacts(); - if( deploymentArtifacts!= null && !deploymentArtifacts.isEmpty()){ - Optional op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); - if(op.isPresent()){ - return Either.left(false); - } - } - Map artifacts = origComponent.getArtifacts(); - if( artifacts!= null && !artifacts.isEmpty()){ - Optional op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny(); - if(op.isPresent()){ - return Either.left(false); - } - } - - } - return result; - } - - private List getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List groups) { - List updatedGroups = new ArrayList<>(); - boolean isUpdated = false; - if (groups != null) { - for (GroupDefinition group : groups) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) { - group.getArtifacts().remove(artifactId); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroups.add(group); - } - } - } - return updatedGroups; - } - - private List getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List groupInstances) { - List updatedGroupInstances = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(groupInstances)) { - boolean isUpdated = false; - for (GroupInstance groupInstance : groupInstances) { - isUpdated = false; - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) { - groupInstance.getGroupInstanceArtifacts().remove(artifactId); - isUpdated = true; - } - if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); - isUpdated = true; - } - if (isUpdated) { - updatedGroupInstances.add(groupInstance); - } - } - } - return updatedGroupInstances; - } - - private Either deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { - - Either result; - boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); - String componentId = component.getUniqueId(); - String instanceId = componentId.equals(parentId) ? null : parentId; - if (isMandatory) { - log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); - resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); - } else if (cloneIsNeeded) { - log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); - result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); - } else { - log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); - result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); - } - return result; - } - - private Either, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { - - Either, ActionStatus> result = null; - Map artifacts = new HashMap<>(); - ComponentInstance foundInstance = null; - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { - Optional componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst(); - if (!componentInstanceOpt.isPresent()) { - result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); - } else { - foundInstance = componentInstanceOpt.get(); - fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); - } - } else { - fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); - } - if (result == null) { - if (artifacts.containsKey(artifactId)) { - result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); - } else { - result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); - } - } - return result; - } - - private void fetchArtifactsFromComponent(String artifactId, Component component, Map artifacts) { - Map currArtifacts; - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { - currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { - currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { - currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - } - - private void fetchArtifactsFromInstance(String artifactId, Map artifacts, ComponentInstance instance) { - Map currArtifacts; - if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { - currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { - currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - if (MapUtils.isNotEmpty(currArtifacts)) { - artifacts.putAll(currArtifacts); - } - } - } - - private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { - StorageOperationStatus result; - switch (cassandraStatus) { - case OK: - result = StorageOperationStatus.OK; - break; - case NOT_FOUND: - result = StorageOperationStatus.NOT_FOUND; - break; - case CLUSTER_NOT_CONNECTED: - case KEYSPACE_NOT_CONNECTED: - result = StorageOperationStatus.CONNECTION_FAILURE; - break; - default: - result = StorageOperationStatus.GENERAL_ERROR; - break; - } - return result; - } - - private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { - if (fetchedArtifact != null) { - log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); - fetchedArtifact.setEsId(null); - fetchedArtifact.setArtifactName(null); - fetchedArtifact.setDescription(null); - fetchedArtifact.setApiUrl(null); - fetchedArtifact.setArtifactChecksum(null); - nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact); - fetchedArtifact.setArtifactUUID(null); - long time = System.currentTimeMillis(); - fetchedArtifact.setPayloadUpdateDate(time); - fetchedArtifact.setHeatParameters(null); - fetchedArtifact.setHeatParamsUpdateDate(null); - } - } - - private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) { - StorageOperationStatus error = StorageOperationStatus.OK; - if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - log.debug("Need to re-generate customization UUID for instance {}", instanceId); - error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId); - } - return error; - } - - private Either, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) { - Either artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId()); - if (artifactById.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); - log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - ArtifactDefinition artifactDefinition = artifactById.left().value(); - if (artifactDefinition == null) { - log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); - handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - Either insideEither = Either.left(artifactDefinition); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); - return Either.left(insideEither); - } - - private Either fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) { - Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId); - if (!(ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) && artifactById.isRight()) { - // in case of update artifact must be - BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); - log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); - } - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && artifactById.isLeft()) { - log.debug("Artifact {} already exist", artifactId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); - } - ArtifactDefinition currentArtifactInfo = null; - if (artifactById.isLeft()) { - // get previous value - currentArtifactInfo = artifactById.left().value(); - } - return Either.left(currentArtifactInfo); - } - - private Either handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, - ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) { - - String artifactLabel = artifactInfo.getArtifactLabel(); - if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) { - BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); - log.debug("missing artifact logical name for component {}", componentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) { - - if (operationName != null) { - if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { - log.debug("artifact label cannot be set {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); - } else { - artifactLabel = operationName; - } - } - String displayName = artifactInfo.getArtifactDisplayName(); - if (displayName == null || displayName.isEmpty()) - displayName = artifactLabel; - displayName = ValidationUtils.cleanArtifactDisplayName(displayName); - // if (!ValidationUtils.validateArtifactDisplayName(displayName)) { - // log.debug("Invalid format form Artifact displayName : {}", displayName); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - // } - artifactInfo.setArtifactDisplayName(displayName); - - if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { - log.debug("Invalid format form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel); - - if (artifactLabel.isEmpty()) { - log.debug("missing normalized artifact logical name for component {}", componentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); - } - - if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) { - log.debug("Invalid lenght form Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); - } - if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) { - log.debug("Non unique Artifact label : {}", artifactLabel); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); - } - } - artifactInfo.setArtifactLabel(artifactLabel); - - return Either.left(ActionStatus.OK); - } - - private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) { - boolean isUnique = true; - Either, StorageOperationStatus> artifacts; - if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { - artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); - } else { - artifacts = artifactToscaOperation.getArtifacts(componentId); - } - - if (artifacts.isLeft()) { - for (String label : artifacts.left().value().keySet()) { - if (label.equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - if (componentType.equals(ComponentTypeEnum.RESOURCE)) { - Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true); - if (allInterfacesOfResource.isLeft()) { - for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { - for (Operation operation : interace.getOperationsMap().values()) { - if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) { - isUnique = false; - break; - } - } - } - } - } - return isUnique; - } - - // *************************************************************** - - private Either, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { - Either, ResponseFormat> resultOp = null; - Either insideEither = null; - ComponentInstance foundInstance = findComponentInstance(parentId, parent); - String instanceId = null; - String instanceName = null; - if (foundInstance != null) { - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); - NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - result.left().value(); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } if (isLeft) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; - } else{ - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; - - } - } - - private Either, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, - ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { - - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - Either, ResponseFormat> resultOp = null; - Either insideEither = null; - ComponentInstance foundInstance = findComponentInstance(parentId, parent); - String instanceId = null; - String instanceName = null; - if (foundInstance != null) { - instanceId = foundInstance.getUniqueId(); - instanceName = foundInstance.getName(); - } - if (artifactData == null) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug("Failed to create artifact object for ES."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); - resultOp = Either.right(responseFormat); - return resultOp; - - } - // set on graph object id of artifact in ES! - artifactInfo.setEsId(artifactData.getId()); - - boolean isLeft = false; - String artifactUniqueId = null; - StorageOperationStatus error = null; - if (interfaceType != null && operationName != null) { - // lifecycle artifact - Operation operation = convertToOperation(artifactInfo, operationName); - - Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getImplementation().getUniqueId(); - result.left().value().getImplementation(); - - insideEither = Either.right(result.left().value()); - resultOp = Either.left(insideEither); - } else { - error = result.right().value(); - } - } else { - // information/deployment/api aritfacts - log.trace("Try to create entry on graph"); - NodeTypeEnum nodeType = convertParentType(componentTypeEnum); - Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId); - - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - result.left().value(); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } else { - error = result.right().value(); - } - } - if (isLeft) { - boolean res = saveArtifacts(artifactData, parentId, false); - // String uniqueId = artifactDefinition.getUniqueId(); - - if (res) { - log.debug("Artifact saved into ES - {}", artifactUniqueId); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); - - resultOp = Either.right(responseFormat); - return resultOp; - } - } else { - log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName()); - handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); - resultOp = Either.right(responseFormat); - return resultOp; - } - - } - - private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { - ComponentInstance foundInstance = null; - if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { - foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); - } - return foundInstance; - } - - private Either validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { - - Either result = Either.left(true); - Wrapper responseWrapper = new Wrapper(); - - validateArtifactTypeExists(responseWrapper, artifactInfo); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - - Map resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); - - if (responseWrapper.isEmpty()) { - validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); - } - - if (responseWrapper.isEmpty()) { - // Common code for all types - // not allowed to change artifactType - if (!isCreate) { - Either validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact); - if (validateServiceApiType.isRight()) { - responseWrapper.setInnerElement(validateServiceApiType.right().value()); - } - } - } - if (responseWrapper.isEmpty()) { - if (parentType.equals(NodeTypeEnum.Resource)) { - // if (parentComponent instanceof Resource) { - Resource resource = (Resource) parentComponent; - ResourceTypeEnum resourceType = resource.getResourceType(); - ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); - if (config == null) { - responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } else { - List myList = config.getValidForResourceTypes(); - Either either = validateResourceType(resourceType, artifactInfo, myList); - if (either.isRight()) { - responseWrapper.setInnerElement(either.right().value()); - } - } - } - } - if (responseWrapper.isEmpty()) { - validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); - } - - if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) { - String artifactName = artifactInfo.getArtifactName(); - if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) { - validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType); - } - } - - if (responseWrapper.isEmpty()) { - switch (artifactType) { - case HEAT: - case HEAT_VOL: - case HEAT_NET: { - result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType); - break; - } - case HEAT_ENV: { - result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType); - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - break; - } - case DCAE_INVENTORY_TOSCA: - case DCAE_INVENTORY_JSON: - case DCAE_INVENTORY_POLICY: - // Validation is done in handle payload. - case DCAE_INVENTORY_DOC: - case DCAE_INVENTORY_BLUEPRINT: - case DCAE_INVENTORY_EVENT: - // No specific validation - default: { - artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); - } - } - - } - - if (!responseWrapper.isEmpty()) { - result = Either.right(responseWrapper.getInnerElement()); - } - return result; - } - - private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper responseWrapper, ArtifactTypeEnum artifactType, Map resourceDeploymentArtifacts) { - if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); - } - } - - private Map fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { - Map resourceDeploymentArtifacts = null; - if (parentType.equals(NodeTypeEnum.Resource)) { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - } else { - resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } - return resourceDeploymentArtifacts; - } - - public void validateArtifactTypeExists(Wrapper responseWrapper, ArtifactDefinition artifactInfo) { - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - if (artifactType == null) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); - } - } - - private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - ArtifactTypeConfig retConfig = null; - String fileType = artifactType.getType(); - if (parentType.equals(NodeTypeEnum.Resource)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType); - } else if (parentType.equals(NodeTypeEnum.Service)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType); - } - return retConfig; - } - - private Either extractHeatParameters(ArtifactDefinition artifactInfo) { - // extract heat parameters - if (artifactInfo.getPayloadData() != null) { - String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType()); - if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { - log.info("failed to parse heat parameters "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType()); - return Either.right(responseFormat); - } else if (heatParameters.isLeft() && heatParameters.left().value() != null) { - artifactInfo.setListHeatParameters(heatParameters.left().value()); - } - } - return Either.left(true); - - } - - // Valid extension - public void validateFileExtension(Wrapper responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { - String fileType = artifactType.getType(); - List acceptedTypes = null; - ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); - if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { - log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return; - } - - if (deploymentAcceptedTypes == null) { - log.debug("parent type of artifact can be either resource or service"); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - return; - } else { - acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); - } - /* - * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. - * - * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}", - * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType : - * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError( - * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; } - */ - - String artifactName = artifactInfo.getArtifactName(); - String fileExtension = GeneralUtility.getFilenameExtension(artifactName); - // Pavel - File extension validation is case-insensitive - Ella, - // 21/02/2016 - if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) { - log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType)); - return; - } - } - - private Either validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - - Wrapper errorWrapper = new Wrapper(); - Wrapper heatMDWrapper = new Wrapper(); - Wrapper payloadWrapper = new Wrapper<>(); - - if (errorWrapper.isEmpty()) { - validateValidYaml(errorWrapper, artifactInfo); - } - - if (errorWrapper.isEmpty()) { - // Validate Heat Exist - validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType()); - } - - // if (errorWrapper.isEmpty() && isCreate) { - // // Validate Only Single HeatEnv Artifact - // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId); - // } - - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); - } - - if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { - validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); - } - - // Init Response - Either eitherResponse; - if (errorWrapper.isEmpty()) { - eitherResponse = Either.left(true); - } else { - eitherResponse = Either.right(errorWrapper.getInnerElement()); - } - return eitherResponse; - } - - public void fillArtifactPayloadValidation(Wrapper errorWrapper, Wrapper payloadWrapper, ArtifactDefinition artifactDefinition) { - if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) { - Either fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition); - if (fillArtifactPayload.isRight()) { - errorWrapper.setInnerElement(fillArtifactPayload.right().value()); - log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); - } - } else { - payloadWrapper.setInnerElement(artifactDefinition.getPayloadData()); - } - } - - public Either fillArtifactPayload(Wrapper payloadWrapper, ArtifactDefinition artifactMD) { - Either result = Either.left(true); - Either eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId()); - if (eitherArtifactData.isLeft()) { - byte[] data = eitherArtifactData.left().value().getDataAsArray(); - data = Base64.encodeBase64(data); - payloadWrapper.setInnerElement(data); - } else { - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); - result = Either.right(responseFormat); - } - return result; - - } - - @SuppressWarnings("unchecked") - private void validateEnvVsHeat(Wrapper errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { - String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); - Map heatEnvToscaJson = (Map) new Yaml().load(envPayload); - String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); - Map heatToscaJson = (Map) new Yaml().load(heatDecodedPayload); - - Either, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS); - Either, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS); - if (eitherHeatEnvProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); - errorWrapper.setInnerElement(responseFormat); - log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); - } else if (eitherHeatProperties.isRight()) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - } else { - Set heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); - Set heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); - heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); - if (heatEnvPropertiesKeys.size() > 0) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName()); - errorWrapper.setInnerElement(responseFormat); - } - } - } - - private void validateValidYaml(Wrapper errorWrapper, ArtifactDefinition artifactInfo) { - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); - if (!isYamlValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType()); - errorWrapper.setInnerElement(responseFormat); - log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName()); - } - } - - public boolean isValidXml(byte[] xmlToParse) { - if(parser == null) { - log.debug("SAX XML Parser have not been initialized"); - return false; - } - boolean isXmlValid = true; - - try { - parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse))); - } catch (IOException | SAXException e) { - log.debug("Xml is invalid : {}", e.getMessage(), e); - isXmlValid = false; - } - - return isXmlValid; - } - - public boolean isValidJson(byte[] jsonToParse) { - String parsed = new String(jsonToParse); - try { - gson.fromJson(parsed, Object.class); - } catch (Exception e) { - log.debug("Json is invalid : {}", e.getMessage(), e); - return false; - } - return true; - } - - public void validateSingleArtifactType(Wrapper errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) { - boolean typeArtifactFound = false; - // Iterator parentDeploymentArtifactsItr = - // (parentType == NodeTypeEnum.Resource) ? - // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource) - // parentComponent).iterator() - // : getDeploymentArtifacts(parentComponent, parentType).iterator(); - - Iterator parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator(); - - while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) { - ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType()); - typeArtifactFound = (foundArtifactType == allowedArtifactType); - } - if (typeArtifactFound) { - String parentName = parentComponent.getName(); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType()); - - errorWrapper.setInnerElement(responseFormat); - log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType()); - - } - } - - public void validateSingleDeploymentArtifactName(Wrapper errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) { - boolean artifactNameFound = false; - // Iterator parentDeploymentArtifactsItr = - // (parentType == NodeTypeEnum.Resource) ? - // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource) - // parentComponent).iterator() - // : getDeploymentArtifacts(parentComponent, parentType).iterator(); - - Iterator parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator(); - - while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) { - artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName())); - } - if (artifactNameFound) { - String parentName = parentComponent.getName(); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName); - - errorWrapper.setInnerElement(responseFormat); - log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); - - } - } - - private void validateHeatExist(String componentId, String parentRiId, Wrapper errorWrapper, Wrapper heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, - ComponentTypeEnum componentType) { - Either res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); - if (res.isRight()) { - ResponseFormat responseFormat; - if (res.right().value() == StorageOperationStatus.NOT_FOUND) { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } else { - responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - } - errorWrapper.setInnerElement(responseFormat); - - return; - } - ArtifactDefinition heatArtifact = res.left().value(); - heatArtifactMDWrapper.setInnerElement(heatArtifact); - // Iterator parentArtifactsItr = parentDeploymentArtifacts.iterator(); - // while (!heatFound && parentArtifactsItr.hasNext()) { - // ArtifactDefinition currArtifact = parentArtifactsItr.next(); - // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) { - // heatFound = true; - // heatArtifactMDWrapper.setInnerElement(currArtifact); - // log.trace("In validateHeatExist found artifact {}", currArtifact); - // /* - // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){ - // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); } - // */ - // } - // } - // if (!heatFound) { - // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); - // errorWrapper.setInnerElement(responseFormat); - // log.debug("Can't create heat env artifact because No heat Artifact exist."); - // } - - } - - private Either validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { - log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); - // timeout > 0 for HEAT artifacts - Integer timeout = artifactInfo.getTimeout(); - Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout(); - if (timeout == null) { - artifactInfo.setTimeout(defaultTimeout); - // HEAT artifact but timeout is invalid - } else if (timeout < 1) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT)); - } - - // US649856 - Allow several HEAT files on Resource - /* - * if (isCreate) { Wrapper errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return - * Either.right(errorWrapper.getInnerElement()); } } - */ - - log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel()); - return Either.left(true); - } - - private Either validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List typeList) { - String listToString = (typeList != null) ? typeList.toString() : ""; - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue()); - Either either = Either.right(responseFormat); - String resourceTypeName = resourceType.name(); - if (typeList != null && typeList.contains(resourceTypeName)) { - either = Either.left(true); - } - return either; - } - - private Either validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { - if (artifactInfo.getHeatParameters() != null) { - for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { - String parameterType = heatParam.getType(); - HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType); - String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType(); - if (heatParameterType == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType()); - return Either.right(responseFormat); - } - - StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty); - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName()); - return Either.right(responseFormat); - } - } - } - return Either.left(artifactInfo); - } - - public List getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) { - List deploymentArtifacts = new ArrayList<>(); - if (parentComponent.getDeploymentArtifacts() != null) { - if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) { - Either getRI = getRIFromComponent(parentComponent, ciId, null, null, null); - if (getRI.isRight()) { - return deploymentArtifacts; - } - ComponentInstance ri = getRI.left().value(); - if (ri.getDeploymentArtifacts() != null) { - deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); - } - } else if (parentComponent.getDeploymentArtifacts() != null) { - deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); - } - } - return deploymentArtifacts; - } - - private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) { - // on create if null add informational to current - if (artifactInfo.getArtifactGroupType() == null) { - artifactInfo.setArtifactGroupType(type); - } - if (artifactInfo.getUniqueId() != null) { - log.error("artifact uniqid cannot be set ignoring"); - } - artifactInfo.setUniqueId(null); - - if (artifactInfo.getArtifactRef() != null) { - log.error("artifact ref cannot be set ignoring"); - } - artifactInfo.setArtifactRef(null); - - if (artifactInfo.getArtifactRepository() != null) { - log.error("artifact repository cannot be set ignoring"); - } - artifactInfo.setArtifactRepository(null); - - if (artifactInfo.getUserIdCreator() != null) { - log.error("creator uuid cannot be set ignoring"); - } - artifactInfo.setArtifactCreator(user.getUserId()); - - if (artifactInfo.getUserIdLastUpdater() != null) { - log.error("userId of last updater cannot be set ignoring"); - } - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - if (artifactInfo.getCreatorFullName() != null) { - log.error("creator Full name cannot be set ignoring"); - } - String fullName = user.getFirstName() + " " + user.getLastName(); - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getUpdaterFullName() != null) { - log.error("updater Full name cannot be set ignoring"); - } - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getCreationDate() != null) { - log.error("Creation Date cannot be set ignoring"); - } - long time = System.currentTimeMillis(); - artifactInfo.setCreationDate(time); - - if (artifactInfo.getLastUpdateDate() != null) { - log.error("Last Update Date cannot be set ignoring"); - } - artifactInfo.setLastUpdateDate(time); - - if (artifactInfo.getEsId() != null) { - log.error("es id cannot be set ignoring"); - } - artifactInfo.setEsId(null); - - } - - /* - * private Either fetchCurrentArtifact(boolean isCreate, String artifactId) { Either artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate - * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId); - * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return - * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return - * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value - * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); } - */ - - private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) { - String id = artifactId; - if (artifactId == null || artifactId.isEmpty()) { - String uniqueId = null; - if (interfaceName != null && operationName != null) { - uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel()); - } else { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()); - } - artifactInfo.setUniqueId(uniqueId); - artifactInfo.setEsId(uniqueId); - id = uniqueId; - } else { - artifactInfo.setUniqueId(artifactId); - artifactInfo.setEsId(artifactId); - } - return id; - } - - private Either validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { - BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); - log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); - } - - boolean artifactTypeExist = false; - Either, ActionStatus> allArtifactTypes = null; - ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); - - if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { - allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType); - } else { - - allArtifactTypes = elementOperation.getAllArtifactTypes(); - } - if (allArtifactTypes.isRight()) { - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); - log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value()); - return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); - } - - for (ArtifactType type : allArtifactTypes.left().value()) { - if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) { - artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase()); - artifactTypeExist = true; - break; - } - } - - if (!artifactTypeExist) { - BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); - log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType())); - } - - return Either.left(ActionStatus.OK); - } - - private Either, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { - - Map deploymentArtifacts = null; - List artifactTypes = new ArrayList(); - - if (parentType.equals(NodeTypeEnum.Service)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - } else { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } - if (deploymentArtifacts != null) { - for (String artifactType : deploymentArtifacts.keySet()) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return Either.left(artifactTypes); - } else { - return Either.right(ActionStatus.GENERAL_ERROR); - } - - } - - private Either validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD)); - } - return Either.left(true); - - } - - private Either validateAndSetArtifactname(ArtifactDefinition artifactInfo) { - if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); - } - - String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName()); - if (normalizeFileName == null || normalizeFileName.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); - } - artifactInfo.setArtifactName(normalizeFileName); - - if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH))); - } - - return Either.left(true); - } - - private Either validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { - log.info("artifact type is missing operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); - } - - if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { - log.info("artifact type cannot be changed operation ignored"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(true); - } - - private Either validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { - if (artifactInfo.getArtifactGroupType() == null) { - artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - } - - else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { - log.info("artifact group type cannot be changed. operation failed"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(artifactInfo); - } - - private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) { - - // on update if null add informational to current - if (currentArtifact.getArtifactGroupType() == null && type != null) { - currentArtifact.setArtifactGroupType(type); - } - - if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) { - log.error("artifact uniqid cannot be set ignoring"); - } - artifactInfo.setUniqueId(currentArtifact.getUniqueId()); - - if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) { - log.error("artifact ref cannot be set ignoring"); - } - artifactInfo.setArtifactRef(currentArtifact.getArtifactRef()); - - if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) { - log.error("artifact repository cannot be set ignoring"); - } - artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository()); - - if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) { - log.error("creator uuid cannot be set ignoring"); - } - artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator()); - - if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) { - log.error("artifact creator cannot be set ignoring"); - } - artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator()); - - if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) { - log.error("userId of last updater cannot be set ignoring"); - } - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) { - log.error("creator Full name cannot be set ignoring"); - } - artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName()); - - if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) { - log.error("updater Full name cannot be set ignoring"); - } - String fullName = user.getFirstName() + " " + user.getLastName(); - artifactInfo.setUpdaterFullName(fullName); - - if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) { - log.error("Creation Date cannot be set ignoring"); - } - artifactInfo.setCreationDate(currentArtifact.getCreationDate()); - - if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) { - log.error("Last Update Date cannot be set ignoring"); - } - long time = System.currentTimeMillis(); - artifactInfo.setLastUpdateDate(time); - - if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) { - log.error("es id cannot be set ignoring"); - } - artifactInfo.setEsId(currentArtifact.getUniqueId()); - - if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) { - log.error(" Artifact Display Name cannot be set ignoring"); - } - artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName()); - - if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) { - log.debug("serviceApi cannot be set. ignoring."); - } - artifactInfo.setServiceApi(currentArtifact.getServiceApi()); - - if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) { - log.debug("artifact group cannot be set. ignoring."); - } - artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); - - artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion()); - - if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) { - log.debug("artifact UUID cannot be set. ignoring."); - } - artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); - - if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) { - checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters()); - } - } - - private void checkAndSetUnupdatableHeatParams(List heatParameters, List currentParameters) { - - Map currentParametersMap = getMapOfParameters(currentParameters); - for (HeatParameterDefinition parameter : heatParameters) { - HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId()); - - if (currentParam != null) { - - if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) { - log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName()); - parameter.setName(currentParam.getName()); - } - if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) { - log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); - parameter.setDefaultValue(currentParam.getDefaultValue()); - } - if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) { - log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType()); - parameter.setType(currentParam.getType()); - } - if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) { - log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription()); - parameter.setDescription(currentParam.getDescription()); - } - - // check and set current value - if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) { - log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue()); - parameter.setCurrentValue(currentParam.getDefaultValue()); - } - } - } - } - - private Map getMapOfParameters(List currentParameters) { - - Map currentParamsMap = new HashMap(); - for (HeatParameterDefinition param : currentParameters) { - currentParamsMap.put(param.getUniqueId(), param); - } - return currentParamsMap; - } - - private Either validateAndServiceApiUrl(ArtifactDefinition artifactInfo) { - if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) { - log.debug("Artifact url cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL)); - } - artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase()); - - if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL)); - } - if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH))); - } - - return Either.left(true); - } - - private Either validateAndCleanDescription(ArtifactDefinition artifactInfo) { - if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) { - log.debug("Artifact description cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION)); - } - String description = artifactInfo.getDescription(); - description = ValidationUtils.removeNoneUtf8Chars(description); - description = ValidationUtils.normaliseWhitespace(description); - description = ValidationUtils.stripOctets(description); - description = ValidationUtils.removeHtmlTagsOnly(description); - if (!ValidationUtils.validateIsEnglish(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH))); - } - artifactInfo.setDescription(description); - return Either.left(true); - } - - private Either, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload, - ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) { - ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); - String prevArtifactId = null; - String currArtifactId = artifactId; - - Either, ResponseFormat> resultOp = null; - Either insideEither = null; - - if (artifactData == null) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to create artifact object for ES."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - log.trace("Try to update entry on graph"); - String artifactUniqueId = null; - ArtifactDefinition artifactDefinition = artifactInfo; - StorageOperationStatus error = null; - - boolean isLeft = false; - if (interfaceType != null && operationName != null) { - // lifecycle artifact - /* - * Operation operation = convertToOperation(artifactInfo, operationName); - * - * Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); - * - * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation(); - * - * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); } - */ - } else { - log.debug("Enty on graph is updated. Update artifact in ES"); - boolean res = true; - // Changing previous and current artifactId for auditing - prevArtifactId = currArtifactId; - currArtifactId = artifactDefinition.getUniqueId(); - - NodeTypeEnum convertParentType = convertParentType(componentType); - - if (decodedPayload == null) { - if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { - Either artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId()); - // Either - // artifactfromES = daoUploader.getArtifact(artifactId); - if (artifactFromCassandra.isRight()) { - log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); - error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - return resultOp; - } - // clone data to new artifact - artifactData.setData(artifactFromCassandra.left().value().getData()); - artifactData.setId(artifactFromCassandra.left().value().getId()); - } - } else { - if (artifactDefinition.getEsId() == null) { - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - artifactData.setId(artifactDefinition.getUniqueId()); - } - } - - Either result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId); - isLeft = result.isLeft(); - if (isLeft) { - artifactUniqueId = result.left().value().getUniqueId(); - artifactDefinition = result.left().value(); - String artifactType = artifactInfo.getArtifactType(); - if (NodeTypeEnum.Resource == convertParentType - && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) { - - if (!artifactUniqueId.equals(artifactId)) { - // need to update the generated id in heat env - Map deploymentArtifacts = parent.getDeploymentArtifacts(); - Optional> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst(); - if (findFirst.isPresent()) { - ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); - artifactEnvInfo.setArtifactChecksum(null); - artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId); - } - } - - /* - * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType); - * - * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either heatEnvEither = - * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId); - * - * } } } - */ - } - error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); - - insideEither = Either.left(result.left().value()); - resultOp = Either.left(insideEither); - if (error != StorageOperationStatus.OK) { - isLeft = false; - } - - } else { - error = result.right().value(); - } - if (isLeft) { - - // create new entry in ES - res = true; - if (artifactData.getData() != null) { - if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) - artifactData.setId(artifactDefinition.getEsId()); - res = saveArtifacts(artifactData, parentId, false); - - } - } - - if (res) { - log.debug("Artifact saved into ES - {}", artifactUniqueId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - // resultOp = Either.left(result.left().value()); - // return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - // return resultOp; - } - } - - return resultOp; - } - - private Either handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) { - log.trace("Starting payload handling"); - byte[] payload = artifactInfo.getPayloadData(); - byte[] decodedPayload = null; - - if (payload != null && payload.length != 0) { - // the generated artifacts were already decoded by the handler - decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload); - if (decodedPayload.length == 0) { - log.debug("Failed to decode the payload."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - - String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload); - artifactInfo.setArtifactChecksum(checkSum); - log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum); - - // Specific payload validations of different types - Either isValidPayload = Either.left(true); - if (isDeploymentArtifact(artifactInfo)) { - log.trace("Starting deployment artifacts payload validation"); - String artifactType = artifactInfo.getArtifactType(); - if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { - isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType); - if (isValidPayload.isLeft()) { - isValidPayload = extractHeatParameters(artifactInfo); - } - } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) { - isValidPayload = validateXmlPayload(decodedPayload, artifactType); - // else - // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType) - // || ){ - } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType) - || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) { - String artifactFileName = artifactInfo.getArtifactName(); - String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase(); - switch (fileExtension) { - case "xml": - isValidPayload = validateXmlPayload(decodedPayload, artifactType); - break; - case "json": - isValidPayload = validateJsonPayload(decodedPayload, artifactType); - break; - case "yml": - case "yaml": - isValidPayload = validateYmlPayload(decodedPayload, artifactType); - break; - } - } - } - if (isValidPayload.isRight()) { - ResponseFormat responseFormat = isValidPayload.right().value(); - return Either.right(responseFormat); - } - - } // null/empty payload is normal if called from metadata update ONLY. - // The validation of whether this is metadata/payload update case is - // currently done separately - else { - if (!isArtifactMetadataUpdate) { - log.debug("Payload is missing."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - return Either.right(responseFormat); - } - } - log.trace("Ended payload handling"); - return Either.left(decodedPayload); - } - - private Either validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) { - // Basic YAML validation - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { - log.debug("Invalid YAML format"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); - return Either.right(responseFormat); - } - if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { - // HEAT specific YAML validation - DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class); - if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) { - log.debug("HEAT doesn't contain required \"heat_template_version\" section."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType); - return Either.right(responseFormat); - } - } - - return Either.left(true); - } - - private Either validateYmlPayload(byte[] decodedPayload, String artifactType) { - Either res = Either.left(true); - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { - log.debug("Invalid YAML format"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); - res = Either.right(responseFormat); - } - - return res; - } - - private Either validateXmlPayload(byte[] payload, String artifactType) { - boolean isXmlValid = isValidXml(payload); - if (!isXmlValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType); - log.debug("Invalid XML content"); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either validateJsonPayload(byte[] payload, String type) { - boolean isJsonValid = isValidJson(payload); - if (!isJsonValid) { - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type); - log.debug("Invalid JSON content"); - return Either.right(responseFormat); - } - return Either.left(true); - } - - public void handleTransaction(Either opState) { - if (opState == null || opState.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - - public Either deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair userResourceAuditPair, boolean shouldLock, - boolean inTransaction) { - User user = new User(); - user.setUserId(userUserId); - Either parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata); - if (parent.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value())); - return Either.right(responseFormat); - } - Either, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName, - false, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); - } - Either result = handleDelete.left().value(); - return Either.left(result.right().value()); - - } - - private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) { - Operation op = new Operation(); - long time = System.currentTimeMillis(); - op.setCreationDate(time); - - String artifactName = artifactInfo.getArtifactName(); - artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName)); - - op.setImplementation(artifactInfo); - op.setLastUpdateDate(time); - return op; - } - - private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) { - String newArtifactName = operationName + "_" + artifactName; - log.trace("converting artifact name {} to {}", artifactName, newArtifactName); - return newArtifactName; - } - - // download by MSO - public Either downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { - - // General validation - if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - artifactName = ValidationUtils.normalizeFileName(artifactName); - - // Resource validation - Either validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); - if (validateResourceNameAndVersion.isRight()) { - return Either.right(validateResourceNameAndVersion.right().value()); - } - - Resource resource = validateResourceNameAndVersion.left().value(); - String resourceId = resource.getUniqueId(); - - // Service validation - Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - Map artifacts = resource.getDeploymentArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Deployment artifacts of resource {} are not found", resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - ArtifactDefinition deploymentArtifact = null; - - for (ArtifactDefinition artifactDefinition : artifacts.values()) { - if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) { - log.debug("Found deployment artifact {}", artifactName); - deploymentArtifact = artifactDefinition; - break; - } - } - - if (deploymentArtifact == null) { - log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - // Downloading the artifact - Either, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null); - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", artifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - // download by MSO - public Either downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { - - // General validation - if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - artifactName = ValidationUtils.normalizeFileName(artifactName); - - // Resource validation - /* - * Either validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return - * Either.right(validateResourceNameAndVersion.right().value()); } - * - * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId(); - */ - - // Service validation - Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - Service service = validateServiceNameAndVersion.left().value(); - - // ResourceInstance validation - Either validateResourceInstance = validateResourceInstance(service, resourceInstanceName); - if (validateResourceInstance.isRight()) { - return Either.right(validateResourceInstance.right().value()); - } - - ComponentInstance resourceInstance = validateResourceInstance.left().value(); - - Map artifacts = resourceInstance.getDeploymentArtifacts(); - - final String finalArtifactName = artifactName; - Predicate filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); - - boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName); - ArtifactDefinition deployableArtifact; - - if (!hasDeploymentArtifacts) { - log.debug("Deployment artifact with name {} not found", artifactName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - log.debug("Found deployment artifact {}", artifactName); - deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get(); - // Downloading the artifact - Either, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service ); - - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", artifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - private Either validateResourceInstance(Service service, String resourceInstanceName) { - - List riList = service.getComponentInstances(); - for (ComponentInstance ri : riList) { - if (ri.getNormalizedName().equals(resourceInstanceName)) - return Either.left(ri); - } - - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName)); - } - - private Either validateServiceNameAndVersion(String serviceName, String serviceVersion) { - - Either, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); - if (serviceListBySystemName.isRight()) { - log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName)); - } - List serviceList = serviceListBySystemName.left().value(); - if (serviceList == null || serviceList.isEmpty()) { - log.debug("Couldn't fetch any service with name {}", serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName)); - } - - Service foundService = null; - for (Service service : serviceList) { - if (service.getVersion().equals(serviceVersion)) { - log.trace("Found service with version {}", serviceVersion); - foundService = service; - break; - } - } - - if (foundService == null) { - log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion)); - } - return Either.left(foundService); - } - - private Either validateResourceNameAndVersion(String resourceName, String resourceVersion) { - - Either resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); - if (resourceListBySystemName.isRight()) { - log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName)); - } - return Either.left(resourceListBySystemName.left().value()); - } - - public Either downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { - // Validation - log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); - if (serviceName == null || serviceVersion == null || artifactName == null) { - log.debug("One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - // Normalizing artifact name - final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); - - // Service validation - Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); - if (validateServiceNameAndVersion.isRight()) { - return Either.right(validateServiceNameAndVersion.right().value()); - } - - String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); - - // Looking for deployment or tosca artifacts - Service service = validateServiceNameAndVersion.left().value(); - - if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { - log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); - } - - Optional foundArtifactOptl = null; - - if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { - foundArtifactOptl = service.getDeploymentArtifacts().values().stream() - // filters artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); - } - if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { - foundArtifactOptl = service.getToscaArtifacts().values().stream() - // filters TOSCA artifact by name - .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); - } - if (!foundArtifactOptl.isPresent()) { - log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); - } - log.debug("Found deployment artifact {}", normalizedArtifactName); - // Downloading the artifact - Either, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service); - if (downloadArtifactEither.isRight()) { - log.debug("Download artifact {} failed", normalizedArtifactName); - return Either.right(downloadArtifactEither.right().value()); - } - log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); - return Either.left(downloadArtifactEither.left().value().getRight()); - } - - public Either, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { - log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); - Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); - if (artifactById.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); - log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); - } - ArtifactDefinition artifactDefinition = artifactById.left().value(); - if (artifactDefinition == null) { - log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); - } - - return downloadArtifact(artifactDefinition, null); - } - - private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) { - boolean found = false; - Map artifactsS = component.getArtifacts(); - if (artifactsS != null) { - for (Map.Entry entry : artifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - Map deploymentArtifactsS = component.getDeploymentArtifacts(); - if (!found && deploymentArtifactsS != null) { - for (Map.Entry entry : deploymentArtifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - Map toscaArtifactsS = component.getToscaArtifacts(); - if (!found && toscaArtifactsS != null) { - for (Map.Entry entry : toscaArtifactsS.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - switch (component.getComponentType()) { - case RESOURCE: - Map interfaces = ((Resource) component).getInterfaces(); - if (!found && interfaces != null) { - for (Map.Entry entry : interfaces.entrySet()) { - Map operations = entry.getValue().getOperationsMap(); - for (Map.Entry entryOp : operations.entrySet()) { - if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - } - break; - case SERVICE: - Map apiArtifacts = ((Service) component).getServiceApiArtifacts(); - if (!found && apiArtifacts != null) { - for (Map.Entry entry : apiArtifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - break; - default: - - } - - return found; - } - - private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) { - - boolean found = false; - List resourceInstances = component.getComponentInstances(); - ComponentInstance resourceInstance = null; - for (ComponentInstance ri : resourceInstances) { - if (ri.getUniqueId().equals(resourceInstanceId)) { - resourceInstance = ri; - break; - } - } - if (resourceInstance != null) { - Map artifacts = resourceInstance.getDeploymentArtifacts(); - if (artifacts != null) { - for (Map.Entry entry : artifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - if (!found) { - artifacts = resourceInstance.getArtifacts(); - if (artifacts != null) { - for (Map.Entry entry : artifacts.entrySet()) { - if (entry.getValue().getUniqueId().equals(artifactId)) { - found = true; - break; - } - } - } - } - } - return found; - } - - private Either validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, - String containerComponentType, boolean inTransaction) { - - ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); - componentForAudit.getNodeType(); - - Either componentResult = toscaOperationFacade.getToscaFullElement(componentId); - - if (componentResult.isRight()) { - ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); - log.debug("Service not found, serviceId {}", componentId); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); - return Either.right(responseFormat); - } - return Either.left(componentResult.left().value()); - } - - private Either validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation, - ComponentTypeEnum componentType) { - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) { - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - String uniqueId = component.getUniqueId(); - log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId); - handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null); - return Either.right(canWork.right().value()); - } - } - return Either.left(true); - } - - private Either validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { - - if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) { - String role = user.getRole(); - if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - return Either.left(true); - } - - private Either validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { - Either validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction); - - if (validateUserExists.isRight()) { - User user = new User(); - user.setUserId(userId); - handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null); - return Either.right(validateUserExists.right().value()); - } - return Either.left(validateUserExists.left().value()); - } - - protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) { - AuditingActionEnum auditingAction = null; - switch (operation.getArtifactOperationEnum()) { - case Create: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD; - break; - case Update: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE; - break; - case Delete: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE; - break; - case Download: - auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD; - break; - default: - break; - } - return auditingAction; - } - - private Either, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) { - String esArtifactId = artifactDefinition.getEsId(); - Either artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {}", actionStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()); - handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null); - - return Either.right(responseFormat); - } - - ESArtifactData esArtifactData = artifactfromES.left().value(); - byte[] data = esArtifactData.getDataAsArray(); - if (data == null) { - log.debug("Artifact data from ES is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName())); - } - String artifactName = artifactDefinition.getArtifactName(); - log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName); - return Either.left(new ImmutablePair(artifactName, data)); - } - - public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { - ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload); - return artifactData; - } - - private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) { - - CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); - - if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { - log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); - } else { - log.info("Failed to save artifact {}.", artifactData.getId()); - return false; - } - return true; - } - - private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) { - return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE)); - } - - private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) { - return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType())); - } - - public Either createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { - Either user = userAdminManager.getUser(userUserId, inTransaction); - if (user.isRight()) { - ResponseFormat responseFormat; - if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); - responseFormat = componentsUtils.getResponseFormat(user.right().value()); - } - return Either.right(responseFormat); - } - - ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType); - return Either.left(artifactDefinition); - } - - public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); - String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE); - String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); - - artifactInfo.setArtifactDisplayName(artifactName); - artifactInfo.setArtifactLabel(logicalName.toLowerCase()); - artifactInfo.setArtifactType(artifactType); - artifactInfo.setDescription(artifactDescription); - artifactInfo.setArtifactGroupType(groupType); - nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo); - - setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo); - - return artifactInfo; - } - - private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) { - String uniqueId = null; - - if (resourceId != null) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); - artifactInfo.setUniqueId(uniqueId); - } - artifactInfo.setUserIdCreator(user.getUserId()); - String fullName = user.getFullName(); - artifactInfo.setUpdaterFullName(fullName); - - long time = System.currentTimeMillis(); - - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - artifactInfo.setMandatory(true); - } - - public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) { - return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); - } - - public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { - return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); - } - - private Either createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { - - byte[] payload = payloadStr.getBytes(); - - ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); - return Either.left(artifactData); - } - - /** - * - * @param artifactDefinition - * @return - */ - public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, String instanceId) { - String payload = generateHeatEnvPayload(artifactDefinition); - String prevUUID = artifactDefinition.getArtifactUUID(); - ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); - return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) - .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); - } - - public Either forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, String instanceId) { - String payload = generateHeatEnvPayload(artifactDefinition); - String prevUUID = artifactDefinition.getArtifactUUID(); - ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); - return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId) - .left() - .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); - } - - private Either updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { - if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - Optional findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); - if (findFirst.isPresent()) { - ComponentInstance relevantInst = findFirst.get(); - List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); + private static final String ARTIFACT_TYPE_OTHER = "OTHER"; + private static final String ARTIFACT_DESCRIPTION = "artifact description"; + private static final String ARTIFACT_LABEL = "artifact label"; + private static final String ARTIFACT_URL = "artifact url"; + private static final String ARTIFACT_NAME = "artifact name"; + private static final String ARTIFACT_PAYLOAD = "artifact payload"; - if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { - updatedGroupInstances.forEach(gi -> { - gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); - gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); - }); - Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); - if (status.isRight()) { - log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); - return Either.right(responseFormat); + private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; + private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; + private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; + + public static final String HEAT_ENV_NAME = "heatEnv"; + public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + public static final String HEAT_ENV_SUFFIX = "env"; + private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension"; + + private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @javax.annotation.Resource + private IInterfaceLifecycleOperation interfaceLifecycleOperation; + @javax.annotation.Resource + private IUserAdminOperation userOperaton; + + @javax.annotation.Resource + private IElementOperation elementOperation; + + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + @javax.annotation.Resource + private UserBusinessLogic userAdminManager; + + @javax.annotation.Resource + private IHeatParametersOperation heatParametersOperation; + + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + + @Autowired + private ToscaExportHandler toscaExportUtils; + + @Autowired + private CsarUtils csarUtils; + + @Autowired + private LifecycleBusinessLogic lifecycleBusinessLogic; + + @Autowired + private IUserBusinessLogic userBusinessLogic; + + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + + @Autowired + private ArtifactsResolver artifactsResolver; + + public enum ArtifactOperationEnum { + CREATE, UPDATE, DELETE, DOWNLOAD, LINK; + + public static boolean isCreateOrLink(ArtifactOperationEnum operation) { + return operation == CREATE || operation == LINK; + } + } + + public class ArtifactOperationInfo { + + private ArtifactOperationEnum artifactOperationEnum; + private boolean isExternalApi; + private boolean ignoreLifecycleState; + + public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) { + this.artifactOperationEnum = artifactOperationEnum; + this.isExternalApi = isExternalApi; + this.ignoreLifecycleState = ignoreLifecycleState; + } + + public boolean isExternalApi() { + return isExternalApi; + } + + public boolean ignoreLifecycleState() { + return ignoreLifecycleState; + } + + public ArtifactOperationEnum getArtifactOperationEnum() { + return artifactOperationEnum; + } + + } + + // new flow US556184 + public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) { + return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false); + } + + public Either, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, + String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) { + + // step 1 - detect auditing type + AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); + // step 2 - check header + if (userId == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId); + handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + // step 3 - check user existence + Either userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction); + if (userResult.isRight()) { + return Either.right(userResult.right().value()); + } + + // step 4 - check user's role + User user = userResult.left().value(); + Either validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation); + if (validateUserRole.isRight()) { + return Either.right(validateUserRole.right().value()); + } + + // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; + Either validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType); + if (validateComponent.isRight()) { + return Either.right(validateComponent.right().value()); + } + component = validateComponent.left().value(); + Either validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation); + if (validateWorkOnResource.isRight()) { + return Either.right(validateWorkOnResource.right().value()); + } + // step 8 + + return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, user, component, + shouldLock, inTransaction, true); + } + + /** + * This Method validates only the Artifact and does not validate user / role / component ect...
+ * For regular usage use
+ * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)} + * + * @return + */ + public Either, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId, + ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + Component parent = component; + Wrapper errorWrapper = new Wrapper<>(); + + AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5); + artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction); + + Either, ResponseFormat> result; + if (errorWrapper.isEmpty()) { + // step 10 + result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, + Component component, Component parent, Wrapper errorWrapper, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition validatedArtifactInfo = artifactInfo; + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation + .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { + Either validateArtifact = validateArtifact(componentId, componentType, artifactId, component); + if (validateArtifact.isRight()) { + ResponseFormat responseFormat = validateArtifact.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + errorWrapper.setInnerElement(validateArtifact.right().value()); + } + else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) { + validatedArtifactInfo = validateArtifact.left().value(); + handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction); + } + } + return validatedArtifactInfo; + } + + private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either validateArtifact, Wrapper errorWrapper, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition validatedArtifact = validateArtifact.left().value(); + + if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) + && ComponentTypeEnum.SERVICE == component.getComponentType()) { + ComponentInstance componentInstance = component.getComponentInstances() + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findAny() + .get(); + Map deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + + ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values() + .stream() + .filter(p -> p.getUniqueId() + .equals(validatedArtifact.getUniqueId())) + .findAny() + .get(); + Either eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance + .getName(), user, componentId, shouldLock, inTransaction); + if (eitherGenerated.isRight()) { + errorWrapper.setInnerElement(eitherGenerated.right().value()); + } + } + } + + private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) { + boolean needGenerate; + needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component + .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType() + .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV + .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo))); + return needGenerate; + } + + private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) { + return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo + .getArtifactType() + .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum()); + } + + public Either, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, + boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) { + + Either, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB); + if (generated.isRight()) { + return generated; + } + byte[] decodedPayload = artifactDefinition.getPayloadData(); + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload)); + return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition + .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null, + shouldLock, inTransaction); + + } + + private Either, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) { + log.debug("tosca artifact generation"); + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) { + Either generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest); + + if (generated.isRight()) { + log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right() + .value()); + + return Either.right(generated.right().value()); + } + byte[] value = generated.left().value(); + artifactInfo.setPayload(value); + + } + else { + Either exportComponent = toscaExportUtils.exportComponent(parent); + if (exportComponent.isRight()) { + log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right() + .value()); + ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status); + return Either.right(responseFormat); + } + log.debug("Tosca yaml exported for component {} ", parent.getUniqueId()); + String payload = exportComponent.left().value().getMainYaml(); + artifactInfo.setPayloadData(payload); + } + return Either.left(Either.left(artifactInfo)); + } + + private Either, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5, + String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) { + if (interfaceName != null && operationName != null) { + interfaceName = interfaceName.toLowerCase(); + operationName = operationName.toLowerCase(); + } + switch (operation.getArtifactOperationEnum()) { + case DOWNLOAD: + if (artifactGenerationRequired(parent, artifactInfo)) { + return generateNotSavedArtifact(parent, artifactInfo); + } + return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent); + case DELETE: + return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction); + case UPDATE: + Either, ResponseFormat> result = null; + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE) + && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) { + result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction); + if (needUpdateGroup && result.isLeft()) { + Either updateResult = result.left().value(); + ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left() + .value(), parent, componentType, componentId); + if (error != ActionStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(error)); } } } + else { + if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) { + result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup); + } + } + if (result == null) { + result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + if (needUpdateGroup && result.isLeft()) { + Either updateResult = result.left().value(); + + ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left() + .value(), parent, componentType); + if (error != ActionStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(error)); + } + } + } + return result; + case CREATE: + return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction); + case LINK: + return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction); + } + return null; + } + + private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) { + List groups = parent.getGroups(); + if (groups != null && !groups.isEmpty()) { + List groupToUpdate = groups.stream() + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfo + .getUniqueId())) + .collect(Collectors.toList()); + if (groupToUpdate != null && !groupToUpdate.isEmpty()) { + groupToUpdate.forEach(g -> { + g.getArtifacts().remove(artifactInfo.getUniqueId()); + g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID()); + g.getArtifacts().add(artAfterUpdate.getUniqueId()); + g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); + } } } - return Either.left(updatedArtDef); - } - - private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { - List heatParameters = artifactDefinition.getListHeatParameters(); - StringBuilder sb = new StringBuilder(); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append("parameters:\n"); - if (heatParameters != null) { - heatParameters.sort(Comparator.comparing(e -> e.getName())); - - List empltyHeatValues = new ArrayList<>(); - - for (HeatParameterDefinition heatParameterDefinition : heatParameters) { - - String heatValue = heatParameterDefinition.getCurrentValue(); - if (!ValidationUtils.validateStringNotEmpty(heatValue)) { - heatValue = heatParameterDefinition.getDefaultValue(); - if (!ValidationUtils.validateStringNotEmpty(heatValue)) { - empltyHeatValues.add(heatParameterDefinition); - continue; - } - } - HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); - if (type != null) { - switch (type) { - case BOOLEAN: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n"); - break; - case NUMBER: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n"); - break; - case COMMA_DELIMITED_LIST: - case JSON: - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n"); - break; - default: - String value = heatValue; - boolean starts = value.startsWith("\""); - boolean ends = value.endsWith("\""); - if (!(starts && ends)) { - starts = value.startsWith("'"); - ends = value.endsWith("'"); - if (!(starts && ends)) { - value = "\"" + value + "\""; - } - } - sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value); - sb.append("\n"); - break; - - } - } - } - if (!empltyHeatValues.isEmpty()) { - empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); - empltyHeatValues.forEach(hv -> { - sb.append(" ").append(hv.getName()).append(":"); - HeatParameterType type = HeatParameterType.isValidType(hv.getType()); - if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { - sb.append(" \"\"").append("\n"); - } else { - sb.append(" ").append("\n"); - } - }); - } - } - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - - // DE265919 fix - String result = sb.toString().replaceAll("\\\\n", "\n"); - - return result; - } - - /** - * - * @param artifactDefinition - * @param payload - * @return - */ - public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, - User modifier, boolean shouldLock, String instanceId) { - return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), - () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); - - } - - public Either forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, - User modifier, boolean shouldLock, String instanceId) { - return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, System::currentTimeMillis, - () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); - - } - - protected Either generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, - boolean shouldLock, Supplier payloadUpdateDateGen, Supplier> esDataCreator, String instanceId) { - - log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) { - - log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - Either artifactDataRes = esDataCreator.get(); - ESArtifactData artifactData = null; - - if (artifactDataRes.isLeft()) { - artifactData = artifactDataRes.left().value(); - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(artifactDataRes.right().value()); - } - String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray()); - String oldCheckSum; - String esArtifactId = artifactDefinition.getEsId(); - Either artifactfromES; - ESArtifactData esArtifactData; - if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { - log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId); - artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus.name(), esArtifactId); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName())); - } - esArtifactData = artifactfromES.left().value(); - oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray()); - } else { - oldCheckSum = artifactDefinition.getArtifactChecksum(); - - } - Either updateArifactDefinitionStatus = null; - - if (shouldLock) { - Either lockComponent = lockComponent(component, "Update Artifact - lock resource: "); - if (lockComponent.isRight()) { - handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null); - return Either.right(lockComponent.right().value()); - } - } - try { - if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { - - artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); - log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - if (updateArifactDefinitionStatus.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId()); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - } - } else { - - oldCheckSum = artifactDefinition.getArtifactChecksum(); - artifactDefinition.setArtifactChecksum(newCheckSum); - // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); - artifactDefinition.setEsId(artifactDefinition.getUniqueId()); - log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); - updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); - - log.trace("Update Payload ", artifactDefinition.getEsId()); - } - if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { - - artifactDefinition = updateArifactDefinitionStatus.left().value(); - artifactData.setId(artifactDefinition.getUniqueId()); - CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); - - if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { - titanDao.commit(); - log.debug("Artifact Saved In ES {}", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - } else { - titanDao.rollback(); - log.info("Failed to save artifact {}.", artifactData.getId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - } - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName()); - log.debug("Failed To update artifact {}", artifactData.getId()); - handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, - ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); - - return Either.right(responseFormat); - - } - } finally { - if (shouldLock) { - graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType()); - } - } - } - - return Either.left(artifactDefinition); - } - - - public Map buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List updatedRequiredArtifacts) { - return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(), - artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters()); - - } - - public Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent, - List updatedRequiredArtifacts, List heatParameters) { - - Map json = new HashMap(); - if (artifactId != null && !artifactId.isEmpty()) - json.put(Constants.ARTIFACT_ID, artifactId); - - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_TYPE, artifactType); - json.put(Constants.ARTIFACT_DESCRIPTION, description); - - if (artifactContent != null) { - String encodedPayload = new String(artifactContent); - - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - log.debug("payload is encoded. perform decode"); - encodedPayload = Base64.encodeBase64String(artifactContent); - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - } - // } - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); - json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() - : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() - : heatParameters); - return json; - } - - public Either, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { - - String jsonStr = gson.toJson(json); - ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; - String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, - artifactDefinitionFromJson, null, jsonStr, null, null, null, user, containerComponent, false, false, true); - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - return Either.left(uploadArtifactToService.left().value()); - } - - private Either, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, - org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - convertParentType(componentType); - String parentId = parent.getUniqueId(); - // Either artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId); - ArtifactDefinition currArtifact = artifactInfo; - - if (origMd5 != null) { - Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); - if (validateMd5.isRight()) { - ResponseFormat responseFormat = validateMd5.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { - Either deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance); - if (deploymentValidationResult.isRight()) { - ResponseFormat responseFormat = deploymentValidationResult.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - - Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); - if (payloadEither.isRight()) { - ResponseFormat responseFormat = payloadEither.right().value(); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } else { // duplicate - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); - return Either.right(responseFormat); - } - } - - // lock resource - if (shouldLock) { - Either lockComponent = lockComponent(parent, "Update Artifact - lock "); - if (lockComponent.isRight()) { - handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null); - return Either.right(lockComponent.right().value()); - } - } - Either, ResponseFormat> resultOp = null; - try { - resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); - return resultOp; - - } finally { - // unlock resource - if (resultOp == null || resultOp.isRight()) { - log.debug("all changes rollback"); - if (false == inTransaction) - titanDao.rollback(); - } else { - log.debug("all changes committed"); - if (false == inTransaction) - titanDao.commit(); - } - if (shouldLock) - componentType = parent.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); - // graphLockOperation.unlockComponent(parentId, parentType); - } - } - - private Either, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, String origMd5) { - - Either, ResponseFormat> resultOp = null; - Either insideEither = null; - /* - * currently getArtifactById does not retrieve heatParameters Either artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value(); - */ - Either getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); - if (getRI.isRight()) { - return Either.right(getRI.right().value()); - } - ComponentInstance ri = getRI.left().value(); - Either getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user); - if (getArtifactRes.isRight()) { - return Either.right(getArtifactRes.right().value()); - } - ArtifactDefinition currArtifact = getArtifactRes.left().value(); - - if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - List currentHeatEnvParams = currArtifact.getListHeatParameters(); - List updatedHeatEnvParams = artifactInfo.getListHeatParameters(); - new ArrayList(); - - // upload - if (origMd5 != null) { - Either, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams, - updatedHeatEnvParams, currArtifact.getArtifactName()); - if (uploadParamsValidationResult.isRight()) { - ResponseFormat responseFormat = uploadParamsValidationResult.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - artifactInfo.setListHeatParameters(updatedHeatEnvParams); - } - - Either validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType()); - if (validateAndConvertHeatParamers.isRight()) { - ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { - // fill reduced heat env parameters List for updating - replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); - currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); - currArtifact.setListHeatParameters(currentHeatEnvParams); - - Either updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); - if (updateArifactRes.isRight()) { - log.debug("Failed to update artifact on graph - {}", artifactId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value())); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); - if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId()); - if (error != StorageOperationStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName()); - return Either.right(responseFormat); - } - - } - insideEither = Either.left(currArtifact); - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName()); - return resultOp; - } - - private void replaceCurrHeatValueWithUpdatedValue(List currentHeatEnvParams, List updatedHeatEnvParams) { - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - String paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - String updatedParamValue = heatEnvParam.getCurrentValue(); - currHeatParam.setCurrentValue(updatedParamValue); + return ActionStatus.OK; + } + + private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) { + List groups = parent.getGroups(); + if (groups != null && !groups.isEmpty()) { + List groupToUpdate = groups.stream() + .filter(g -> g.getArtifacts() != null && g.getArtifacts() + .contains(artifactInfoHeat + .getUniqueId())) + .collect(Collectors.toList()); + if (groupToUpdate != null && !groupToUpdate.isEmpty()) { + groupToUpdate.forEach(g -> { + g.getArtifacts().remove(artifactInfoHeat.getUniqueId()); + g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID()); + g.getArtifacts().remove(artifactInfoHeatE.getUniqueId()); + g.getArtifacts().add(artHeatAfterUpdate.getUniqueId()); + g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID()); + g.getArtifacts().add(artHEAfterUpdate.getUniqueId()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); } } } - } - - private Either, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, - ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) { - - Either, ResponseFormat> resultOp = null; - Either insideEither = null; - /* - * currently getArtifactById does not retrieve heatParameters Either artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value(); - */ - String currentHeatId = currHeatArtifact.getUniqueId(); - - String esArtifactId = currHeatArtifact.getEsId(); - Either artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); - if (artifactfromES.isRight()) { - CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); - StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); - log.debug("Error when getting artifact from ES, error: {}", actionStatus.name()); - return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName())); - } - - ESArtifactData esArtifactData = artifactfromES.left().value(); - ArtifactDefinition updatedHeatArt = currHeatArtifact; - - List updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); - List currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); - List newHeatEnvParams = new ArrayList(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { - - String paramName; - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue == null) - updatedParamValue = heatEnvParam.getDefaultValue(); - HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); - if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); - - } - currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); - newHeatEnvParams.add(currHeatParam); - break; - } - } - } - if (!newHeatEnvParams.isEmpty()) { - currHeatArtifact.setListHeatParameters(currentHeatEnvParams); - Either operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); - - if (operationStatus.isRight()) { - log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value())); - return Either.right(responseFormat); - - } - updatedHeatArt = operationStatus.left().value(); - boolean res = true; - if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) - esArtifactData.setId(updatedHeatArt.getEsId()); - res = saveArtifacts(esArtifactData, parent.getUniqueId(), false); - - if (res) { - log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null); - // resultOp = Either.left(result.left().value()); - // return resultOp; - } else { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); - log.debug("Failed to save the artifact."); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null); - resultOp = Either.right(responseFormat); - // return resultOp; - } - - insideEither = Either.left(updatedHeatArt); - } - } - Either updateHeatEnvArtifact; - if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { - artifactEnvInfo.setArtifactChecksum(null); - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId); - } else { - updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType()); - - } - if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { - ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType); - if (result != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(result); - return Either.right(responseFormat); - } - } - - if (updatedHeatEnvParams.isEmpty()) { - return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType); - } - resultOp = Either.left(insideEither); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return resultOp; - - } - - private Either,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); - return Either.right(responseFormat); - } - - - private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) { - StorageOperationStatus error = StorageOperationStatus.OK; - log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId()); - List groupsInstances = ri.getGroupInstances(); - // List associatedGroups = null; - List groupInstancesId = null; - if (groupsInstances != null && !groupsInstances.isEmpty()) { - groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList()); - } - if (groupInstancesId != null && !groupInstancesId.isEmpty()) { - // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId())); - toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); - } - return error; - - } - - public Either, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType, - String riName, List currentHeatEnvParams, List updatedHeatEnvParams, String currArtifactName) { - - if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); - return Either.right(responseFormat); - } - - for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) { - String paramName = uploadedHeatParam.getName(); - boolean isExistsInHeat = false; - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - isExistsInHeat = true; - uploadedHeatParam.setType(currHeatParam.getType()); - uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue()); - uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue()); - uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId()); - break; - } - } - if (!isExistsInHeat) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName); - handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); - return Either.right(responseFormat); - } - } - return Either.left(updatedHeatEnvParams); - } - - private Either getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { - ResponseFormat responseFormat = null; - List ris = component.getComponentInstances(); - for (ComponentInstance ri : ris) { - if (riID.equals(ri.getUniqueId())) { - return Either.left(ri); - } - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID); - log.debug("Resource Instance not found, resourceInstanceId {}", riID); - handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null); - return Either.right(responseFormat); - } - - private Either getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { - ResponseFormat responseFormat = null; - Map rtifactsMap = ri.getDeploymentArtifacts(); - for (ArtifactDefinition artifact : rtifactsMap.values()) { - if (artifactId.equals(artifact.getUniqueId())) { - return Either.left(artifact); - } - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId()); - handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName()); - return Either.right(responseFormat); - } - - public ArtifactDefinition extractArtifactDefinition(Either eitherArtifact) { - ArtifactDefinition ret; - if (eitherArtifact.isLeft()) { - ret = eitherArtifact.left().value(); - } else { - ret = eitherArtifact.right().value().getImplementationArtifact(); - } - return ret; - } - - /** - * downloads artifact of component by UUIDs - * - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param auditAdditionalParam - * @return - */ - public Either downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map auditAdditionalParam) { - Wrapper errorWrapper = new Wrapper<>(); - Either result; - byte[] downloadedArtifact = null; - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - /** - * downloads an artifact of resource instance of component by UUIDs - * - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param auditAdditionalParam - * @return - */ - public Either downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map auditAdditionalParam) { - Wrapper errorWrapper = new Wrapper<>(); - Either result; - byte[] downloadedArtifact = null; - ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - if (errorWrapper.isEmpty()) { - downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName()); - } - if (errorWrapper.isEmpty()) { - result = Either.left(downloadedArtifact); - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - /** - * uploads an artifact to a component by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param additionalParams - * @param operation - * @return - */ - public Either uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map additionalParams, - ArtifactOperationInfo operation) { - Wrapper errorWrapper = new Wrapper<>(); - Either, ResponseFormat> actionResult = null; - Either uploadArtifactResult; - ArtifactDefinition uploadArtifact = null; - Component component = null; - String componentId = null; - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - uploadArtifact = actionResult.left().value().left().value(); - uploadArtifactResult = Either.left(uploadArtifact); - } else { - uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); - return uploadArtifactResult; - } - - /** - * upload an artifact to a resource instance by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param additionalParams - * @param operation - * @return - */ - public Either uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, - Map additionalParams, ArtifactOperationInfo operation) { - Wrapper errorWrapper = new Wrapper<>(); - Either uploadArtifactResult; - Either, ResponseFormat> actionResult = null; - ArtifactDefinition uploadArtifact = null; - Component component = null; - String componentInstanceId; - String componentId; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - uploadArtifact = actionResult.left().value().left().value(); - uploadArtifactResult = Either.left(uploadArtifact); - } else { - uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); - return uploadArtifactResult; - } - - /** - * updates an artifact on a component by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, - Map additionalParams, ArtifactOperationInfo operation) { - Wrapper errorWrapper = new Wrapper<>(); - Either updateArtifactResult; - Either, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); - - } else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); - return updateArtifactResult; - } - - /** - * updates an artifact on a resource instance by UUID - * - * @param data - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map additionalParams, ArtifactOperationInfo operation) { - - Wrapper errorWrapper = new Wrapper<>(); - Either updateArtifactResult; - Either, ResponseFormat> actionResult = null; - ArtifactDefinition updateArtifact = null; - Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - updateArtifact = actionResult.left().value().left().value(); - updateArtifactResult = Either.left(updateArtifact); - } else { - updateArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); - return updateArtifactResult; - } - - /** - * deletes an artifact on a component by UUID - * - * @param request - * @param componentType - * @param componentUuid - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map additionalParams, - ArtifactOperationInfo operation) { - - Wrapper errorWrapper = new Wrapper<>(); - Either deleteArtifactResult; - Either, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; - Component component = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); - } - if (errorWrapper.isEmpty()) { - componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); - String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); - if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); - if (component != null) { - componentId = component.getUniqueId(); - componentName = component.getName(); - } - } - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); - } - if (errorWrapper.isEmpty()) { - artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); - } - if (errorWrapper.isEmpty()) { - actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); - } else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); - return deleteArtifactResult; - } - - /** - * deletes an artifact from a resource instance by UUID - * - * @param request - * @param componentType - * @param componentUuid - * @param resourceInstanceName - * @param artifactUUID - * @param additionalParams - * @param operation - * TODO - * @return - */ - public Either deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, - Map additionalParams, ArtifactOperationInfo operation) { - - Wrapper errorWrapper = new Wrapper<>(); - Either deleteArtifactResult; - Either, ResponseFormat> actionResult = null; - ArtifactDefinition deleteArtifact = null; - Component component = null; - String componentInstanceId = null; - String componentId = null; - String artifactId = null; - String origMd5 = request.getHeader(Constants.MD5_HEADER); - String userId = request.getHeader(Constants.USER_ID_HEADER); - ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - if (component == null) { - componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); - } else { - componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); - } - } - if (errorWrapper.isEmpty()) { - componentInstanceId = componentRiPair.getRight().getUniqueId(); - componentId = componentRiPair.getLeft().getUniqueId(); - artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); - } - if (errorWrapper.isEmpty()) { - - actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType)); - - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - } - } - if (errorWrapper.isEmpty()) { - deleteArtifact = actionResult.left().value().left().value(); - deleteArtifactResult = Either.left(deleteArtifact); - } else { - deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); - } - updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); - return deleteArtifactResult; - } - - private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper errorWrapper) { - String artifactId = null; - ArtifactDefinition foundArtifact = null; - if (instance.getDeploymentArtifacts() != null) { - foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); - } - if (foundArtifact == null && instance.getArtifacts() != null) { - foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null); - } - if (foundArtifact == null) { - log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); - } else { - artifactId = foundArtifact.getUniqueId(); - } - return artifactId; - } - - @SuppressWarnings("unchecked") - public Either createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, - Map existingEnvVersions) { - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - if (deploymentResourceArtifacts == null) { - log.debug("no deployment artifacts are configured for generated artifacts"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - Map placeHolderData = (Map) deploymentResourceArtifacts.get(envType); - if (placeHolderData == null) { - log.debug("no env type {} are configured for generated artifacts", envType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - Either createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); - if (createArtifactPlaceHolder.isRight()) { - return Either.right(createArtifactPlaceHolder.right().value()); - } - ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); - artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); - artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); - artifactHeatEnv.setTimeout(0); - buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData); - // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow - handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); - ArtifactDefinition heatEnvPlaceholder; - // Evg : for resource instance artifact will be added later as block with other env artifacts from BL - if (parentType != NodeTypeEnum.ResourceInstance) { - Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component.getUniqueId(), parentType, parentId); - if (addHeatEnvArtifact.isRight()) { - log.debug("failed to create heat env artifact on resource instance"); - return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null)); - } - heatEnvPlaceholder = createArtifactPlaceHolder.left().value(); - } else { - heatEnvPlaceholder = artifactHeatEnv; - artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); - setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); - } - // audit - EnumMap artifactAuditingFields = createArtifactAuditingFields(heatEnvPlaceholder, "", heatEnvPlaceholder.getUniqueId()); - artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName); - ComponentTypeEnum componentType = component.getComponentType(); - if (parentType == NodeTypeEnum.ResourceInstance) { - componentType = ComponentTypeEnum.RESOURCE_INSTANCE; - } - componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields); - return Either.left(heatEnvPlaceholder); - } - - private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { - if (artifact.getListHeatParameters() == null) { - return; - } - List heatEnvParameters = new ArrayList<>(); - for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { - HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); - heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); - heatEnvParameter.setCurrentValue(null); - heatEnvParameters.add(heatEnvParameter); + return ActionStatus.OK; + } + + private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) { + List updatedGroupInstances = new ArrayList<>(); + List groupInstances = null; + Optional componentInstOp = parent.getComponentInstances() + .stream() + .filter(ci -> ci.getUniqueId().equals(parentId)) + .findFirst(); + if (componentInstOp.isPresent()) { + groupInstances = componentInstOp.get().getGroupInstances(); + } + if (CollectionUtils.isNotEmpty(groupInstances)) { + boolean isUpdated = false; + for (GroupInstance groupInstance : groupInstances) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() + .contains(artifactInfo + .getUniqueId())) { + groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId()); + groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId()); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid() + .contains(artifactInfo + .getArtifactUUID())) { + groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID()); + groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroupInstances.add(groupInstance); + } + } + } + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", parent.getUniqueId()); + return componentsUtils.convertFromStorageResponse(status.right().value()); + } + return ActionStatus.OK; + } + + Either, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) { + Either, ResponseFormat> result; + if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) { + result = generateToscaArtifact(parent, artifactInfo, false, false); + } + else { + String heatArtifactId = artifactInfo.getGeneratedFromId(); + Either heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId); + if (heatRes.isRight()) { + log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo + .getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes + .right() + .value()), ""); + return Either.right(responseFormat); + } + String generatedPayload = generateHeatEnvPayload(heatRes.left().value()); + artifactInfo.setPayloadData(generatedPayload); + result = Either.left(Either.left(artifactInfo)); + } + return result; + } + + private Either, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) { + convertParentType(componentType); + String parentId = parent.getUniqueId(); + Either artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo + .getGeneratedFromId()); + ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value(); + + if (origMd5 != null) { + Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { + + Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + else { // duplicate + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + + // lock resource + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + try { + resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup); + return resultOp; + + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + if (!inTransaction) { + titanDao.rollback(); + } + } + else { + log.debug("all changes committed"); + if (!inTransaction) { + titanDao.commit(); + } + } + if (shouldLock) { + graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType()); + } + } + } + + public Either, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) { + if (artifactGenerationRequired(component, csarArtifact)) { + Either generated = csarUtils.createCsar(component, false, false); + + if (generated.isRight()) { + log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right() + .value()); + + return Either.right(generated.right().value()); + } + return Either.left(new ImmutablePair(csarArtifact.getArtifactName(), generated.left() + .value())); + } + return downloadArtifact(csarArtifact); + } + + public Either, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) { + // perform all validation in common flow + Either, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, + null, parentId, containerComponentType); + if (result.isRight()) { + return Either.right(result.right().value()); + } + ArtifactDefinition artifactDefinition; + Either insideValue = result.left().value(); + if (insideValue.isLeft()) { + artifactDefinition = insideValue.left().value(); + } + else { + artifactDefinition = insideValue.right().value().getImplementationArtifact(); + } + // for tosca artifacts and heat env on VF level generated on download without saving + if (artifactDefinition.getPayloadData() != null) { + return Either.left(new ImmutablePair(artifactDefinition.getArtifactName(), artifactDefinition + .getPayloadData())); + } + return downloadArtifact(artifactDefinition); + } + + public Either, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) { + // step 1 + // detect auditing type + Map resMap = null; + Either, ResponseFormat> resultOp = null; + + new Wrapper<>(); + // step 2 + // check header + if (userId == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + } + // step 3 + // check user existence + // step 4 + // check user's role + + Either userResult = validateUserExists(userId, "get artifacts", false); + if (userResult.isRight()) { + + resultOp = Either.right(userResult.right().value()); + return resultOp; + } + + userResult.left().value(); + + // steps 5 - 6 - 7 + // 5. check service/resource existence + // 6. check service/resource check out + // 7. user is owner of checkout state + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; + ComponentParametersView componentFilter = new ComponentParametersView(); + componentFilter.disableAll(); + componentFilter.setIgnoreArtifacts(false); + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + componentFilter.setIgnoreComponentInstances(false); + } + + Either validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum + .findByParamName(containerComponentType), componentFilter); + + if (validateComponent.isRight()) { + resultOp = Either.right(validateComponent.right().value()); + return resultOp; + } + component = validateComponent.left().value(); + Either lockComponent = lockComponent(component, "Update Artifact - lock "); + if (lockComponent.isRight()) { + + resultOp = Either.right(lockComponent.right().value()); + return resultOp; + } + + try { + ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType); + + if (groupType == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + + resultOp = Either.right(responseFormat); + return resultOp; + + } + if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { + List list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); + if (list != null && !list.isEmpty()) { + resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); + } + else { + resMap = new HashMap<>(); + } + resultOp = Either.left(resMap); + return resultOp; + } + else { + + Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType + .getNodeType(), groupType, componentId); + if (artifactsMapStatus.isRight()) { + if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); + resultOp = Either.right(responseFormat); + } + else { + resMap = new HashMap<>(); + resultOp = Either.left(resMap); + } + } + else { + resMap = artifactsMapStatus.left().value(); + resultOp = Either.left(resMap); + } + return resultOp; + } + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + titanDao.rollback(); + } + else { + log.debug("all changes committed"); + titanDao.commit(); + } + + componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } + + } + + private Either validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) { + // step 9 + // check artifact existence + Either artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component + .getUniqueId()); + if (artifactResult.isRight()) { + if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); + log.debug("addArtifact - artifact {} not found", artifactId); + return Either.right(responseFormat); + + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult + .right() + .value())); + log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right() + .value()); + return Either.right(responseFormat); + } + } + // step 9.1 + // check artifact belong to component + boolean found = false; + switch (componentType) { + case RESOURCE: + case SERVICE: + found = checkArtifactInComponent(component, artifactId); + break; + case RESOURCE_INSTANCE: + found = checkArtifactInResourceInstance(component, componentId, artifactId); + break; + default: + + } + if (!found) { + String componentName = componentType.name().toLowerCase(); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName); + log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId); + return Either.right(responseFormat); + } + return Either.left(artifactResult.left().value()); + } + + private Either, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + String artifactId = null; + + // step 11 + Either payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); + if (payloadEither.isRight()) { + return Either.right(payloadEither.right().value()); + } + byte[] decodedPayload = payloadEither.left().value(); + convertParentType(componentType); + + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + + try { + resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName); + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + + } + + } + + private Either, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType, + Component parent, boolean shouldLock, boolean inTransaction) { + + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Upload Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + + try { + resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction); + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + + } + + } + + private Either, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + convertParentType(componentType); + + // lock resource + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Update Artifact - lock "); + + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + + Either, ResponseFormat> resultOp = null; + try { + resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName); + return resultOp; + + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + } + } + + private Either, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, + ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) { + + Either payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName); + + if (payloadEither.isRight()) { + return Either.right(payloadEither.right().value()); + } + byte[] decodedPayload = payloadEither.left().value(); + + return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction); + } + + private Either validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + Component parent, String origMd5, String originData, String interfaceType, String operationName) { + // Md5 validations + Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + // step 11 + Either validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent); + if (validateResult.isRight()) { + ResponseFormat responseFormat = validateResult.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(validateResult.right().value()); + } + + Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + log.debug("Error during handle payload"); + return Either.right(responseFormat); + } + + // validate heat parameters. this part must be after the parameters are + // extracted in "handlePayload" + Either validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo + .getArtifactType()); + if (validateAndConvertHeatParamers.isRight()) { + ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); + handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null); + log.debug("Error during handle payload"); + return Either.right(responseFormat); + } + return payloadEither; + } + + public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, + ComponentTypeEnum componentTypeEnum, String resourceInstanceName) { + + if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType() + .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) { + return; + } + String artifactData = buildAuditingArtifactData(artifactDefinition); + + if (user == null) { + user = new User(); + user.setUserId("UNKNOWN"); + } + switch (componentTypeEnum) { + case RESOURCE: + Resource resource = (Resource) component; + if (resource == null) { + // In that case, component ID should be instead of name + resource = new Resource(); + resource.setName(componentId); + } + componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum, + ResourceAuditData.newBuilder() + .artifactUuid(prevArtifactUuid) + .build(), currentArtifactUuid, artifactData); + break; + + case SERVICE: + Service service = (Service) component; + if (service == null) { + // In that case, component ID should be instead of name + service = new Service(); + service.setName(componentId); + } + componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(), + null, null, artifactData, null); + break; + + case RESOURCE_INSTANCE: + if (resourceInstanceName == null) { + resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId); + } + componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, + ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(), + ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(), + resourceInstanceName, null, artifactData, null); + break; + default: + break; + } + } + + private String getResourceInstanceNameFromComponent(Component component, String componentId) { + ComponentInstance resourceInstance = component.getComponentInstances() + .stream() + .filter(p -> p.getUniqueId().equals(componentId)) + .findFirst() + .orElse(null); + String resourceInstanceName = null; + if (resourceInstance != null) { + resourceInstanceName = resourceInstance.getName(); + } + return resourceInstanceName; + } + + public Map createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) { + Map auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + // Putting together artifact info + String artifactData = buildAuditingArtifactData(artifactDefinition); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid); + return auditingFields; + } + + // ----- + + private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) { + StringBuilder sb = new StringBuilder(); + if (artifactDefinition != null) { + sb.append(artifactDefinition.getArtifactGroupType().getType()) + .append(",") + .append("'") + .append(artifactDefinition.getArtifactLabel()) + .append("'") + .append(",") + .append(artifactDefinition.getArtifactType()) + .append(",") + .append(artifactDefinition.getArtifactName()) + .append(",") + .append(artifactDefinition.getTimeout()) + .append(",") + .append(artifactDefinition.getEsId()); + + sb.append(","); + if (artifactDefinition.getArtifactVersion() != null) { + + sb.append(artifactDefinition.getArtifactVersion()); + } + else { + sb.append(" "); + } + sb.append(","); + if (artifactDefinition.getArtifactUUID() != null) { + sb.append(artifactDefinition.getArtifactUUID()); + } + else { + sb.append(" "); + } + } + return sb.toString(); + } + + private Either validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) { + + if (origMd5 != null) { + String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData); + if (!encodeBase64Str.equals(origMd5)) { + log.debug("The calculated md5 is different then the received one"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + } + } + else { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) { + log.debug("Missing md5 header during artifact create"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5)); + } + // Update metadata + if (payload != null && payload.length != 0) { + log.debug("Cannot have payload while md5 header is missing"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + return Either.left(true); + } + + private Either validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName, + ComponentTypeEnum componentType, Component parentComponent) { + + Either artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId); + if (artifactById.isRight()) { + return Either.right(artifactById.right().value()); + } + ArtifactDefinition currentArtifactInfo = artifactById.left().value(); + + ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo); + Either validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent); + if (validateInformationalArtifactRes.isRight()) { + return Either.right(validateInformationalArtifactRes.right().value()); + } + Either validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo); + if (validateAndSetArtifactname.isRight()) { + return Either.right(validateAndSetArtifactname.right().value()); + } + if (operationName != null && interfaceName != null) { + operationName = operationName.toLowerCase(); + interfaceName = interfaceName.toLowerCase(); + } + Either logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType); + if (logicalNameStatus.isRight()) { + return Either.right(logicalNameStatus.right().value()); + } + // This is a patch to block possibility of updating service api fields + // through other artifacts flow + + ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL; + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType); + } + else { + checkCreateFields(user, artifactInfo, artifactGroupType); + } + + composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName); + if (currentArtifactInfo != null) { + artifactInfo.setMandatory(currentArtifactInfo.getMandatory()); + } + + // artifactGroupType is not allowed to be updated + if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + Either validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo); + if (validateGroupType.isRight()) { + return Either.right(validateGroupType.right().value()); + } + } + // TODO TEMP !!! + NodeTypeEnum parentType = convertParentType(componentType); + + // TODO TEMP !!! + boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()); + + if (isDeploymentArtifact(artifactInfo)) { + Either deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType); + if (deploymentValidationResult.isRight()) { + return Either.right(deploymentValidationResult.right().value()); + } + } + else { + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + } + + Either descriptionResult = validateAndCleanDescription(artifactInfo); + if (descriptionResult.isRight()) { + return Either.right(descriptionResult.right().value()); + } + + if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType() + .equals(ArtifactGroupTypeEnum.SERVICE_API)) { + Either validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType); + if (validateServiceApiType.isRight()) { + return Either.right(validateServiceApiType.right().value()); + } + // Change of type is not allowed and should be ignored + + artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER); + + Either validateUrl = validateAndServiceApiUrl(artifactInfo); + if (validateUrl.isRight()) { + return Either.right(validateUrl.right().value()); + } + + Either validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo); + if (validateUpdate.isRight()) { + log.debug("serviceApi first update cnnot be without payload."); + return Either.right(validateUpdate.right().value()); + } + } + else { + Either validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType); + if (validateArtifactType.isRight()) { + return Either.right(validateArtifactType.right().value()); + } + if (artifactInfo.getApiUrl() != null) { + artifactInfo.setApiUrl(null); + log.error("Artifact URL cannot be set through this API - ignoring"); + } + + if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) { + artifactInfo.setServiceApi(false); + log.error("Artifact service API flag cannot be changed - ignoring"); + } + } + + return Either.left(artifactInfo); + } + + private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) { + if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) { + artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType()); + artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType()); + artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel()); + } + } + + private Either findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { + + Either result = null; + ArtifactDefinition foundArtifact = null; + if (StringUtils.isNotEmpty(artifactId)) { + foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); + } + if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + log.debug("Artifact {} already exist", artifactId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel())); + } + if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + } + if (result == null) { + result = Either.left(foundArtifact); + } + return result; + } + + private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { + ArtifactDefinition foundArtifact; + if (parentComponent.getUniqueId().equals(parentId)) { + foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); + } + else { + ComponentInstance instance = findComponentInstance(parentId, parentComponent); + foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); + } + return foundArtifact; + } + + private Either validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { + ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + Either validationResult = Either.left(true); + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) { + String artifactTypeName = artifactType.getType(); + ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType(); + Map resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInformationalArtifacts(); + Set validArtifactTypes = resourceInformationalArtifacts.keySet(); + if (!validArtifactTypes.contains(artifactTypeName)) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } + else { + List validResourceType = resourceInformationalArtifacts.get(artifactTypeName) + .getValidForResourceTypes(); + if (!validResourceType.contains(parentResourceType.name())) { + validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName)); + } + } + } + return validationResult; + } + + private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) { + if (componentType.equals(ComponentTypeEnum.RESOURCE)) { + return NodeTypeEnum.Resource; + } + else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + return NodeTypeEnum.ResourceInstance; + } + else { + return NodeTypeEnum.Service; + } + } + + public Either, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, + boolean shouldLock, boolean inTransaction) { + + NodeTypeEnum parentType = convertParentType(componentType); + Either, ResponseFormat> resultOp = null; + Either, ActionStatus> getArtifactRes = null; + ArtifactDefinition foundArtifact = null; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + Either getContainerRes = null; + org.openecomp.sdc.be.model.Component fetchedContainerComponent = null; + boolean isDuplicated = false; + String esId = null; + Either needCloneRes = null; + try { + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Delete Artifact - lock resource: "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + resultOp = Either.right(lockComponent.right().value()); + } + } + if (resultOp == null) { + log.debug("Going to fetch the container component {}. ", parent.getUniqueId()); + getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId()); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes + .right() + .value()), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null) { + fetchedContainerComponent = getContainerRes.left().value(); + log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId()); + getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType); + if (getArtifactRes.isRight()) { + log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent + .getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right() + .value(), artifactId); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + else { + foundArtifact = getArtifactRes.left().value().getLeft(); + esId = foundArtifact.getEsId(); + } + } + if (resultOp == null && StringUtils.isNotEmpty(esId)) { + needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent + .getComponentType())); + if (needCloneRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + boolean isNeedToDeleteArtifactFromDB = true; + if (resultOp == null) { + + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + String instanceId = parentId; + Either isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId); + + if (isOnlyResourceInstanceArtifact.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right() + .value(), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value(); + } + + Either updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes + .left() + .value()); + if (updatedArtifactRes.isRight()) { + log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + else { + isDuplicated = updatedArtifactRes.left().value().getDuplicated(); + } + } + + if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) { + log.debug("Going to delete the artifact {} from the database. ", artifactId); + CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId); + if (cassandraStatus != CassandraOperationStatus.OK) { + log.debug("Failed to delete the artifact {} from the database. ", artifactId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + + List updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes + .left() + .value() + .getRight() + .getGroupInstances()); + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + } + if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact + .getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) { + List updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent + .getGroups()); + if (CollectionUtils.isNotEmpty(updatedGroups)) { + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId()); + responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status + .right() + .value()), foundArtifact.getArtifactDisplayName()); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + } + if (resultOp == null) { + resultOp = Either.left(Either.left(foundArtifact)); + handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null); + } + return resultOp; + } + finally { + if (shouldLock) { + unlockComponent(resultOp, parent, inTransaction); + } + } + } + + private Either isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) { + Either result = Either.left(true); + ComponentInstance foundInstance = null; + Optional componentInstanceOpt = parent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId().equals(instanceId)) + .findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } + else { + foundInstance = componentInstanceOpt.get(); + String componentUid = foundInstance.getComponentUid(); + Either getContainerRes = toscaOperationFacade.getToscaElement(componentUid); + if (getContainerRes.isRight()) { + log.debug("Failed to fetch the container component {}. ", componentUid); + return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value())); + } + Component origComponent = getContainerRes.left().value(); + Map deploymentArtifacts = origComponent.getDeploymentArtifacts(); + if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) { + Optional op = deploymentArtifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return Either.left(false); + } + } + Map artifacts = origComponent.getArtifacts(); + if (artifacts != null && !artifacts.isEmpty()) { + Optional op = artifacts.keySet() + .stream() + .filter(a -> a.equals(foundArtifact.getArtifactLabel())) + .findAny(); + if (op.isPresent()) { + return Either.left(false); + } + } + + } + return result; + } + + private List getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List groups) { + List updatedGroups = new ArrayList<>(); + boolean isUpdated = false; + if (groups != null) { + for (GroupDefinition group : groups) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) { + group.getArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid() + .contains(foundArtifact.getArtifactUUID())) { + group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroups.add(group); + } + } + } + return updatedGroups; + } + + private List getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List groupInstances) { + List updatedGroupInstances = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(groupInstances)) { + boolean isUpdated = false; + for (GroupInstance groupInstance : groupInstances) { + isUpdated = false; + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts() + .contains(artifactId)) { + groupInstance.getGroupInstanceArtifacts().remove(artifactId); + isUpdated = true; + } + if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid() + .contains(foundArtifact + .getArtifactUUID())) { + groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); + isUpdated = true; + } + if (isUpdated) { + updatedGroupInstances.add(groupInstance); + } + } + } + return updatedGroupInstances; + } + + private Either deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) { + + Either result; + boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi(); + String componentId = component.getUniqueId(); + String instanceId = componentId.equals(parentId) ? null : parentId; + if (isMandatory) { + log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); + resetMandatoryArtifactFields(foundArtifact); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true); + } + else if (cloneIsNeeded) { + log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); + } + else { + log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId); + result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false); + } + return result; + } + + private Either, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) { + + Either, ActionStatus> result = null; + Map artifacts = new HashMap<>(); + ComponentInstance foundInstance = null; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) { + Optional componentInstanceOpt = fetchedContainerComponent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId() + .equals(parentId)) + .findFirst(); + if (!componentInstanceOpt.isPresent()) { + result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER); + } + else { + foundInstance = componentInstanceOpt.get(); + fetchArtifactsFromInstance(artifactId, artifacts, foundInstance); + } + } + else { + fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts); + } + if (result == null) { + if (artifacts.containsKey(artifactId)) { + result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance)); + } + else { + result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND); + } + } + return result; + } + + private void fetchArtifactsFromComponent(String artifactId, Component component, Map artifacts) { + Map currArtifacts; + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { + currArtifacts = component.getDeploymentArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) { + currArtifacts = component.getToscaArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private void fetchArtifactsFromInstance(String artifactId, Map artifacts, ComponentInstance instance) { + Map currArtifacts; + if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) { + currArtifacts = instance.getDeploymentArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) { + currArtifacts = instance.getArtifacts() + .values() + .stream() + .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); + if (MapUtils.isNotEmpty(currArtifacts)) { + artifacts.putAll(currArtifacts); + } + } + } + + private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) { + StorageOperationStatus result; + switch (cassandraStatus) { + case OK: + result = StorageOperationStatus.OK; + break; + case NOT_FOUND: + result = StorageOperationStatus.NOT_FOUND; + break; + case CLUSTER_NOT_CONNECTED: + case KEYSPACE_NOT_CONNECTED: + result = StorageOperationStatus.CONNECTION_FAILURE; + break; + default: + result = StorageOperationStatus.GENERAL_ERROR; + break; + } + return result; + } + + private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) { + if (fetchedArtifact != null) { + log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId()); + fetchedArtifact.setEsId(null); + fetchedArtifact.setArtifactName(null); + fetchedArtifact.setDescription(null); + fetchedArtifact.setApiUrl(null); + fetchedArtifact.setArtifactChecksum(null); + nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact); + fetchedArtifact.setArtifactUUID(null); + long time = System.currentTimeMillis(); + fetchedArtifact.setPayloadUpdateDate(time); + fetchedArtifact.setHeatParameters(null); + fetchedArtifact.setHeatParamsUpdateDate(null); + } + } + + private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) { + StorageOperationStatus error = StorageOperationStatus.OK; + if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + log.debug("Need to re-generate customization UUID for instance {}", instanceId); + error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + return error; + } + + private Either, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, + Component parent) { + Either artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent + .getUniqueId()); + if (artifactById.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); + log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, ""); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + ArtifactDefinition artifactDefinition = artifactById.left().value(); + if (artifactDefinition == null) { + log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""); + handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + Either insideEither = Either.left(artifactDefinition); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null); + return Either.left(insideEither); + } + + private Either handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName, + ComponentTypeEnum componentType) { + + String artifactLabel = artifactInfo.getArtifactLabel(); + if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel() + .isEmpty())) { + BeEcompErrorManager.getInstance() + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + log.debug("missing artifact logical name for component {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); + } + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) { + + if (operationName != null) { + if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) { + log.debug("artifact label cannot be set {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED)); + } + else { + artifactLabel = operationName; + } + } + String displayName = artifactInfo.getArtifactDisplayName(); + if (displayName == null || displayName.isEmpty()) { + displayName = artifactLabel; + } + displayName = ValidationUtils.cleanArtifactDisplayName(displayName); + artifactInfo.setArtifactDisplayName(displayName); + + if (!ValidationUtils.validateArtifactLabel(artifactLabel)) { + log.debug("Invalid format form Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel); + + if (artifactLabel.isEmpty()) { + log.debug("missing normalized artifact logical name for component {}", componentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL)); + } + + if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) { + log.debug("Invalid lenght form Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String + .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH))); + } + if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) { + log.debug("Non unique Artifact label : {}", artifactLabel); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel)); + } + } + artifactInfo.setArtifactLabel(artifactLabel); + + return Either.left(ActionStatus.OK); + } + + private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) { + boolean isUnique = true; + Either, StorageOperationStatus> artifacts; + if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) { + artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId); + } + else { + artifacts = artifactToscaOperation.getArtifacts(componentId); + } + + if (artifacts.isLeft()) { + for (String label : artifacts.left().value().keySet()) { + if (label.equals(artifactLabel)) { + isUnique = false; + break; + } + } + } + if (componentType.equals(ComponentTypeEnum.RESOURCE)) { + Either, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation + .getAllInterfacesOfResource(componentId, true, true); + if (allInterfacesOfResource.isLeft()) { + for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) { + for (Operation operation : interace.getOperationsMap().values()) { + if (operation.getImplementation() != null && operation.getImplementation() + .getArtifactLabel() + .equals(artifactLabel)) { + isUnique = false; + break; + } + } + } + } + } + return isUnique; + } + + // *************************************************************** + + private Either, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) { + Either, ResponseFormat> resultOp = null; + Either insideEither = null; + ComponentInstance foundInstance = findComponentInstance(parentId, parent); + String instanceId = null; + String instanceName = null; + if (foundInstance != null) { + instanceId = foundInstance.getUniqueId(); + instanceName = foundInstance.getName(); + } + boolean isLeft = false; + String artifactUniqueId = null; + StorageOperationStatus error = null; + // information/deployment/api aritfacts + log.trace("Try to create entry on graph"); + NodeTypeEnum nodeType = convertParentType(componentTypeEnum); + Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent + .getUniqueId(), nodeType, true, instanceId); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + result.left().value(); + + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + if (isLeft) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + return resultOp; + } + else { + log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo + .getArtifactDisplayName()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); + resultOp = Either.right(responseFormat); + return resultOp; + + } + } + + private Either, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user, + ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) { + + ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); + Either, ResponseFormat> resultOp = null; + Either insideEither = null; + ComponentInstance foundInstance = findComponentInstance(parentId, parent); + String instanceId = null; + String instanceName = null; + if (foundInstance != null) { + if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) { + log.debug("Failed to create artifact, already exists"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo + .getArtifactLabel()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance + .getName()); + resultOp = Either.right(responseFormat); + return resultOp; + } + + instanceId = foundInstance.getUniqueId(); + instanceName = foundInstance.getName(); + } + if (artifactData == null) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); + log.debug("Failed to create artifact object for ES."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null); + resultOp = Either.right(responseFormat); + return resultOp; + + } + // set on graph object id of artifact in ES! + artifactInfo.setEsId(artifactData.getId()); + + boolean isLeft = false; + String artifactUniqueId = null; + StorageOperationStatus error = null; + if (interfaceType != null && operationName != null) { + // lifecycle artifact + Operation operation = convertToOperation(artifactInfo, operationName); + + Either result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getImplementation().getUniqueId(); + result.left().value().getImplementation(); + + insideEither = Either.right(result.left().value()); + resultOp = Either.left(insideEither); + } + else { + error = result.right().value(); + } + } + else { + // information/deployment/api aritfacts + log.trace("Try to create entry on graph"); + NodeTypeEnum nodeType = convertParentType(componentTypeEnum); + Either result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent + .getUniqueId(), nodeType, true, instanceId); + + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + artifactData.setId(result.left().value().getEsId()); + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + else { + error = result.right().value(); + } + } + if (isLeft) { + boolean res = saveArtifacts(artifactData, parentId); + + if (res) { + log.debug("Artifact saved into ES - {}", artifactUniqueId); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + return resultOp; + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName); + + resultOp = Either.right(responseFormat); + return resultOp; + } + } + else { + log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo + .getArtifactDisplayName()); + handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName); + resultOp = Either.right(responseFormat); + return resultOp; + } + + } + + private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + foundInstance = containerComponent.getComponentInstances() + .stream() + .filter(i -> i.getUniqueId().equals(componentInstanceId)) + .findFirst() + .orElse(null); + } + return foundInstance; + } + + private Either validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) { + + Either result = Either.left(true); + Wrapper responseWrapper = new Wrapper(); + + validateArtifactTypeExists(responseWrapper, artifactInfo); + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + + Map resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType); + + if (responseWrapper.isEmpty()) { + validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts); + } + + // Common code for all types + // not allowed to change artifactType + if (responseWrapper.isEmpty() && !isCreate) { + Either validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact); + if (validateServiceApiType.isRight()) { + responseWrapper.setInnerElement(validateServiceApiType.right().value()); + } + } + if (responseWrapper.isEmpty()) { + if (parentType.equals(NodeTypeEnum.Resource)) { + Resource resource = (Resource) parentComponent; + ResourceTypeEnum resourceType = resource.getResourceType(); + ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType()); + if (config == null) { + responseWrapper.setInnerElement(ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + else { + List myList = config.getValidForResourceTypes(); + Either either = validateResourceType(resourceType, artifactInfo, myList); + if (either.isRight()) { + responseWrapper.setInnerElement(either.right().value()); + } + } + } + + validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType); + } + + if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) { + String artifactName = artifactInfo.getArtifactName(); + if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) { + validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType); + } + } + + if (responseWrapper.isEmpty()) { + switch (artifactType) { + case HEAT: + case HEAT_VOL: + case HEAT_NET: + result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact); + break; + case HEAT_ENV: + result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType); + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; + case DCAE_INVENTORY_TOSCA: + case DCAE_INVENTORY_JSON: + case DCAE_INVENTORY_POLICY: + // Validation is done in handle payload. + case DCAE_INVENTORY_DOC: + case DCAE_INVENTORY_BLUEPRINT: + case DCAE_INVENTORY_EVENT: + // No specific validation + default: + artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT); + break; + } + + } + + if (!responseWrapper.isEmpty()) { + result = Either.right(responseWrapper.getInnerElement()); + } + return result; + } + + private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper responseWrapper, ArtifactTypeEnum artifactType, Map resourceDeploymentArtifacts) { + if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + } + } + + private Map fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) { + Map resourceDeploymentArtifacts = null; + if (parentType.equals(NodeTypeEnum.Resource)) { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts(); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); + } + else { + resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts(); + } + return resourceDeploymentArtifacts; + } + + public void validateArtifactTypeExists(Wrapper responseWrapper, ArtifactDefinition artifactInfo) { + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); + if (artifactType == null) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType()); + } + } + + private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + ArtifactTypeConfig retConfig = null; + String fileType = artifactType.getType(); + if (parentType.equals(NodeTypeEnum.Resource)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts() + .get(fileType); + } + else if (parentType.equals(NodeTypeEnum.Service)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts() + .get(fileType); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + retConfig = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts() + .get(fileType); + } + return retConfig; + } + + private Either extractHeatParameters(ArtifactDefinition artifactInfo) { + // extract heat parameters + if (artifactInfo.getPayloadData() != null) { + String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData())); + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo + .getArtifactType()); + if (heatParameters.isRight() && (!heatParameters.right() + .value() + .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) { + log.info("failed to parse heat parameters "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo + .getArtifactType()); + return Either.right(responseFormat); + } + else if (heatParameters.isLeft() && heatParameters.left().value() != null) { + artifactInfo.setListHeatParameters(heatParameters.left().value()); + } + } + return Either.left(true); + + } + + // Valid extension + public void validateFileExtension(Wrapper responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) { + String fileType = artifactType.getType(); + List acceptedTypes = null; + ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig(); + if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) { + log.debug("parent type of artifact can be either resource or service"); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return; + } + + if (deploymentAcceptedTypes == null) { + log.debug("parent type of artifact can be either resource or service"); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + return; + } + else { + acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes(); + } + /* + * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted. + */ + + String artifactName = artifactInfo.getArtifactName(); + String fileExtension = GeneralUtility.getFilenameExtension(artifactName); + // Pavel - File extension validation is case-insensitive - Ella, + // 21/02/2016 + if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) { + log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType)); + return; + } + } + + private Either validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { + + Wrapper errorWrapper = new Wrapper(); + Wrapper heatMDWrapper = new Wrapper(); + Wrapper payloadWrapper = new Wrapper<>(); + + if (errorWrapper.isEmpty()) { + validateValidYaml(errorWrapper, artifactInfo); + } + + if (errorWrapper.isEmpty()) { + // Validate Heat Exist + validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent + .getComponentType()); + } + + if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { + fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement()); + } + + if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) { + validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement()); + } + + // init Response + Either eitherResponse; + if (errorWrapper.isEmpty()) { + eitherResponse = Either.left(true); + } + else { + eitherResponse = Either.right(errorWrapper.getInnerElement()); + } + return eitherResponse; + } + + public void fillArtifactPayloadValidation(Wrapper errorWrapper, Wrapper payloadWrapper, ArtifactDefinition artifactDefinition) { + if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) { + Either fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition); + if (fillArtifactPayload.isRight()) { + errorWrapper.setInnerElement(fillArtifactPayload.right().value()); + log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName()); + } + } + else { + payloadWrapper.setInnerElement(artifactDefinition.getPayloadData()); + } + } + + public Either fillArtifactPayload(Wrapper payloadWrapper, ArtifactDefinition artifactMD) { + Either result = Either.left(true); + Either eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD + .getEsId()); + if (eitherArtifactData.isLeft()) { + byte[] data = eitherArtifactData.left().value().getDataAsArray(); + data = Base64.encodeBase64(data); + payloadWrapper.setInnerElement(data); + } + else { + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData + .right() + .value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus)); + result = Either.right(responseFormat); + } + return result; + + } + + @SuppressWarnings("unchecked") + private void validateEnvVsHeat(Wrapper errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) { + String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData())); + Map heatEnvToscaJson = (Map) new Yaml().load(envPayload); + String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData)); + Map heatToscaJson = (Map) new Yaml().load(heatDecodedPayload); + + Either, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS); + Either, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS); + if (eitherHeatEnvProperties.isRight()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env"); + errorWrapper.setInnerElement(responseFormat); + log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName()); + } + else if (eitherHeatProperties.isRight()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact + .getArtifactName(), heatArtifact.getArtifactName()); + errorWrapper.setInnerElement(responseFormat); + log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact + .getArtifactName()); + } + else { + Set heatPropertiesKeys = eitherHeatProperties.left().value().keySet(); + Set heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet(); + heatEnvPropertiesKeys.removeAll(heatPropertiesKeys); + if (!heatEnvPropertiesKeys.isEmpty()) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact + .getArtifactName(), heatArtifact.getArtifactName()); + errorWrapper.setInnerElement(responseFormat); + } + } + } + + private void validateValidYaml(Wrapper errorWrapper, ArtifactDefinition artifactInfo) { + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData()); + if (!isYamlValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo + .getArtifactType()); + errorWrapper.setInnerElement(responseFormat); + log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName()); + } + } + + private boolean isValidXml(byte[] xmlToParse) { + boolean isXmlValid = true; + try { + XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + setFeatures(reader); + reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse))); + } + catch (ParserConfigurationException | IOException | SAXException e) { + log.debug("Xml is invalid : {}", e.getMessage(), e); + isXmlValid = false; + } + return isXmlValid; + } + + private void setFeatures(XMLReader reader) throws SAXNotSupportedException { + try { + reader.setFeature("http://apache.org/xml/features/validation/schema", false); + reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + } + catch (SAXNotRecognizedException e) { + log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e); + } + } + + private boolean isValidJson(byte[] jsonToParse) { + String parsed = new String(jsonToParse); + try { + gson.fromJson(parsed, Object.class); + } + catch (Exception e) { + log.debug("Json is invalid : {}", e.getMessage(), e); + return false; + } + return true; + } + + private void validateSingleDeploymentArtifactName(Wrapper errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) { + boolean artifactNameFound = false; + Iterator parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null) + .iterator(); + + while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) { + artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()); + } + if (artifactNameFound) { + String parentName = parentComponent.getName(); + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType + .name(), parentName, artifactName); + + errorWrapper.setInnerElement(responseFormat); + log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName); + + } + } + + private void validateHeatExist(String componentId, String parentRiId, Wrapper errorWrapper, Wrapper heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType, + ComponentTypeEnum componentType) { + Either res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType); + if (res.isRight()) { + ResponseFormat responseFormat; + if (res.right().value() == StorageOperationStatus.NOT_FOUND) { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } + else { + responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT); + } + errorWrapper.setInnerElement(responseFormat); + return; + } + ArtifactDefinition heatArtifact = res.left().value(); + heatArtifactMDWrapper.setInnerElement(heatArtifact); + } + + private Either validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel()); + // timeout > 0 for HEAT artifacts + Integer timeout = artifactInfo.getTimeout(); + if (timeout == null) { + Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout(); + artifactInfo.setTimeout(defaultTimeout); + // HEAT artifact but timeout is invalid + } + else if (timeout < 1) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT)); + } + + // US649856 - Allow several HEAT files on Resource + log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel()); + return Either.left(true); + } + + private Either validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List typeList) { + String listToString = (typeList != null) ? typeList.toString() : ""; + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo + .getArtifactName(), listToString, resourceType.getValue()); + Either either = Either.right(responseFormat); + String resourceTypeName = resourceType.name(); + if (typeList != null && typeList.contains(resourceTypeName)) { + either = Either.left(true); + } + return either; + } + + private Either validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) { + if (artifactInfo.getHeatParameters() != null) { + for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) { + String parameterType = heatParam.getType(); + HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType); + String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType(); + if (heatParameterType == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam + .getType()); + return Either.right(responseFormat); + } + + StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty); + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam + .getType(), heatParam.getName()); + return Either.right(responseFormat); + } + } + } + return Either.left(artifactInfo); + } + + public List getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) { + List deploymentArtifacts = new ArrayList<>(); + if (parentComponent.getDeploymentArtifacts() != null) { + if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) { + Either getRI = getRIFromComponent(parentComponent, ciId, null, null, null); + if (getRI.isRight()) { + return deploymentArtifacts; + } + ComponentInstance ri = getRI.left().value(); + if (ri.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); + } + } + else if (parentComponent.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); + } + } + return deploymentArtifacts; + } + + private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) { + // on create if null add informational to current + if (artifactInfo.getArtifactGroupType() == null) { + artifactInfo.setArtifactGroupType(type); + } + if (artifactInfo.getUniqueId() != null) { + log.error("artifact uniqid cannot be set ignoring"); + } + artifactInfo.setUniqueId(null); + + if (artifactInfo.getArtifactRef() != null) { + log.error("artifact ref cannot be set ignoring"); + } + artifactInfo.setArtifactRef(null); + + if (artifactInfo.getArtifactRepository() != null) { + log.error("artifact repository cannot be set ignoring"); + } + artifactInfo.setArtifactRepository(null); + + if (artifactInfo.getUserIdCreator() != null) { + log.error("creator uuid cannot be set ignoring"); + } + artifactInfo.setArtifactCreator(user.getUserId()); + + if (artifactInfo.getUserIdLastUpdater() != null) { + log.error("userId of last updater cannot be set ignoring"); + } + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + if (artifactInfo.getCreatorFullName() != null) { + log.error("creator Full name cannot be set ignoring"); + } + String fullName = user.getFirstName() + " " + user.getLastName(); + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getUpdaterFullName() != null) { + log.error("updater Full name cannot be set ignoring"); + } + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getCreationDate() != null) { + log.error("Creation Date cannot be set ignoring"); + } + long time = System.currentTimeMillis(); + artifactInfo.setCreationDate(time); + + if (artifactInfo.getLastUpdateDate() != null) { + log.error("Last Update Date cannot be set ignoring"); + } + artifactInfo.setLastUpdateDate(time); + + if (artifactInfo.getEsId() != null) { + log.error("es id cannot be set ignoring"); + } + artifactInfo.setEsId(null); + + } + + + private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) { + String id = artifactId; + if (artifactId == null || artifactId.isEmpty()) { + String uniqueId = null; + if (interfaceName != null && operationName != null) { + uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo + .getArtifactLabel()); + } + else { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()); + } + artifactInfo.setUniqueId(uniqueId); + artifactInfo.setEsId(uniqueId); + id = uniqueId; + } + else { + artifactInfo.setUniqueId(artifactId); + artifactInfo.setEsId(artifactId); + } + return id; + } + + private Either validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) { + if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { + BeEcompErrorManager.getInstance() + .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel"); + log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); + } + + boolean artifactTypeExist = false; + Either, ActionStatus> allArtifactTypes = null; + ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType(); + + if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { + allArtifactTypes = getDeploymentArtifactTypes(parentType); + } + else { + + allArtifactTypes = elementOperation.getAllArtifactTypes(); + } + if (allArtifactTypes.isRight()) { + BeEcompErrorManager.getInstance() + .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes + .right() + .value() + .name()); + log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right() + .value()); + return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId)); + } + + for (ArtifactType type : allArtifactTypes.left().value()) { + if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) { + artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase()); + artifactTypeExist = true; + break; + } + } + + if (!artifactTypeExist) { + BeEcompErrorManager.getInstance() + .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo + .getArtifactType(), "Artifact " + artifactInfo.getArtifactName()); + log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo + .getArtifactType())); + } + + return Either.left(ActionStatus.OK); + } + + private Either, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { + + Map deploymentArtifacts ; + List artifactTypes = new ArrayList(); + + if (parentType.equals(NodeTypeEnum.Service)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getServiceDeploymentArtifacts(); + } + else if (parentType.equals(NodeTypeEnum.ResourceInstance)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceInstanceDeploymentArtifacts(); + } + else { + deploymentArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getResourceDeploymentArtifacts(); + } + if (deploymentArtifacts != null) { + for (String artifactType : deploymentArtifacts.keySet()) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return Either.left(artifactTypes); + } + else { + return Either.right(ActionStatus.GENERAL_ERROR); + } + + } + + private Either validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD)); + } + return Either.left(true); + + } + + private Either validateAndSetArtifactname(ArtifactDefinition artifactInfo) { + if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); + } + + String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName()); + if (normalizeFileName == null || normalizeFileName.isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME)); + } + artifactInfo.setArtifactName(normalizeFileName); + + if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH))); + } + + return Either.left(true); + } + + private Either validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) { + log.info("artifact type is missing operation ignored"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE)); + } + + if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) { + log.info("artifact type cannot be changed operation ignored"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(true); + } + + private Either validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) { + if (artifactInfo.getArtifactGroupType() == null) { + artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); + } + + else if (!currentArtifact.getArtifactGroupType() + .getType() + .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) { + log.info("artifact group type cannot be changed. operation failed"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(artifactInfo); + } + + private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) { + + // on update if null add informational to current + if (currentArtifact.getArtifactGroupType() == null && type != null) { + currentArtifact.setArtifactGroupType(type); + } + + if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) { + log.error("artifact uniqid cannot be set ignoring"); + } + artifactInfo.setUniqueId(currentArtifact.getUniqueId()); + + if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef() + .equals(artifactInfo.getArtifactRef())) { + log.error("artifact ref cannot be set ignoring"); + } + artifactInfo.setArtifactRef(currentArtifact.getArtifactRef()); + + if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository() + .equals(artifactInfo.getArtifactRepository())) { + log.error("artifact repository cannot be set ignoring"); + } + artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository()); + + if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator() + .equals(artifactInfo.getUserIdCreator())) { + log.error("creator uuid cannot be set ignoring"); + } + artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator()); + + if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator() + .equals(artifactInfo.getArtifactCreator())) { + log.error("artifact creator cannot be set ignoring"); + } + artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator()); + + if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater() + .equals(artifactInfo.getUserIdLastUpdater())) { + log.error("userId of last updater cannot be set ignoring"); + } + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName() + .equals(artifactInfo.getCreatorFullName())) { + log.error("creator Full name cannot be set ignoring"); + } + artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName()); + + if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName() + .equals(artifactInfo.getUpdaterFullName())) { + log.error("updater Full name cannot be set ignoring"); + } + String fullName = user.getFirstName() + " " + user.getLastName(); + artifactInfo.setUpdaterFullName(fullName); + + if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate() + .equals(artifactInfo.getCreationDate())) { + log.error("Creation Date cannot be set ignoring"); + } + artifactInfo.setCreationDate(currentArtifact.getCreationDate()); + + if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate() + .equals(artifactInfo.getLastUpdateDate())) { + log.error("Last Update Date cannot be set ignoring"); + } + long time = System.currentTimeMillis(); + artifactInfo.setLastUpdateDate(time); + + if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) { + log.error("es id cannot be set ignoring"); + } + artifactInfo.setEsId(currentArtifact.getUniqueId()); + + if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName() + .equals(artifactInfo.getArtifactDisplayName())) { + log.error(" Artifact Display Name cannot be set ignoring"); + } + artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName()); + + if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi() + .equals(artifactInfo.getServiceApi())) { + log.debug("serviceApi cannot be set. ignoring."); + } + artifactInfo.setServiceApi(currentArtifact.getServiceApi()); + + if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType() + .equals(artifactInfo.getArtifactGroupType())) { + log.debug("artifact group cannot be set. ignoring."); + } + artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType()); + + artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion()); + + if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID() + .isEmpty() && !currentArtifact.getArtifactUUID() + .equals(artifactInfo.getArtifactUUID())) { + log.debug("artifact UUID cannot be set. ignoring."); + } + artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID()); + + if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo + .getHeatParameters() + .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) { + checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters()); + } + } + + private void checkAndSetUnupdatableHeatParams(List heatParameters, List currentParameters) { + + Map currentParametersMap = getMapOfParameters(currentParameters); + for (HeatParameterDefinition parameter : heatParameters) { + HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId()); + + if (currentParam != null) { + + if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) { + log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName()); + parameter.setName(currentParam.getName()); + } + if (parameter.getDefaultValue() != null && !parameter.getDefaultValue() + .equalsIgnoreCase(currentParam.getDefaultValue())) { + log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue()); + parameter.setDefaultValue(currentParam.getDefaultValue()); + } + if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) { + log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType()); + parameter.setType(currentParam.getType()); + } + if (parameter.getDescription() != null && !parameter.getDescription() + .equalsIgnoreCase(currentParam.getDescription())) { + log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription()); + parameter.setDescription(currentParam.getDescription()); + } + + // check and set current value + if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) { + log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue()); + parameter.setCurrentValue(currentParam.getDefaultValue()); + } + } + } + } + + private Map getMapOfParameters(List currentParameters) { + + Map currentParamsMap = new HashMap(); + for (HeatParameterDefinition param : currentParameters) { + currentParamsMap.put(param.getUniqueId(), param); + } + return currentParamsMap; + } + + private Either validateAndServiceApiUrl(ArtifactDefinition artifactInfo) { + if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) { + log.debug("Artifact url cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL)); + } + artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase()); + + if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL)); + } + if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH))); + } + + return Either.left(true); + } + + private Either validateAndCleanDescription(ArtifactDefinition artifactInfo) { + if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) { + log.debug("Artifact description cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION)); + } + String description = artifactInfo.getDescription(); + description = ValidationUtils.removeNoneUtf8Chars(description); + description = ValidationUtils.normaliseWhitespace(description); + description = ValidationUtils.stripOctets(description); + description = ValidationUtils.removeHtmlTagsOnly(description); + if (!ValidationUtils.validateIsEnglish(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String + .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH))); + } + artifactInfo.setDescription(description); + return Either.left(true); + } + + private Either, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload, + ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) { + ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload); + String prevArtifactId = null; + String currArtifactId = artifactId; + + Either, ResponseFormat> resultOp = null; + Either insideEither = null; + + if (artifactData == null) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to create artifact object for ES."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + return resultOp; + } + log.trace("Try to update entry on graph"); + String artifactUniqueId = null; + ArtifactDefinition artifactDefinition = artifactInfo; + StorageOperationStatus error; + + boolean isLeft; + if (!(interfaceType != null && operationName != null)) { + log.debug("Enty on graph is updated. Update artifact in ES"); + boolean res = true; + // Changing previous and current artifactId for auditing + prevArtifactId = currArtifactId; + currArtifactId = artifactDefinition.getUniqueId(); + + NodeTypeEnum convertParentType = convertParentType(componentType); + + if (decodedPayload == null) { + if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) { + Either artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition + .getEsId()); + if (artifactFromCassandra.isRight()) { + log.debug("Failed to get artifact data from ES for artifact id {}", artifactId); + error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right() + .value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + return resultOp; + } + // clone data to new artifact + artifactData.setData(artifactFromCassandra.left().value().getData()); + artifactData.setId(artifactFromCassandra.left().value().getId()); + } + } + else { + if (artifactDefinition.getEsId() == null) { + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + artifactData.setId(artifactDefinition.getUniqueId()); + } + } + + Either result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent + .getUniqueId(), artifactId, convertParentType, parentId); + isLeft = result.isLeft(); + if (isLeft) { + artifactUniqueId = result.left().value().getUniqueId(); + artifactDefinition = result.left().value(); + String artifactType = artifactInfo.getArtifactType(); + if (NodeTypeEnum.Resource == convertParentType + && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) + && !artifactUniqueId.equals(artifactId)) { + // need to update the generated id in heat env + Map deploymentArtifacts = parent.getDeploymentArtifacts(); + Optional> findFirst = deploymentArtifacts.entrySet() + .stream() + .filter(a -> a.getValue() + .getGeneratedFromId() != null && a + .getValue() + .getGeneratedFromId() + .equals(artifactId)) + .findFirst(); + if (findFirst.isPresent()) { + ArtifactDefinition artifactEnvInfo = findFirst.get().getValue(); + artifactEnvInfo.setArtifactChecksum(null); + artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId); + } + } + error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType); + + insideEither = Either.left(result.left().value()); + resultOp = Either.left(insideEither); + if (error != StorageOperationStatus.OK) { + isLeft = false; + } + + } + else { + error = result.right().value(); + } + if (isLeft) { + + // create new entry in ES + res = true; + if (artifactData.getData() != null) { + if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) { + artifactData.setId(artifactDefinition.getEsId()); + } + res = saveArtifacts(artifactData, parentId); + + } + } + + if (res) { + log.debug("Artifact saved into ES - {}", artifactUniqueId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + } + + return resultOp; + } + + private Either handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) { + log.trace("Starting payload handling"); + byte[] payload = artifactInfo.getPayloadData(); + byte[] decodedPayload = null; + + if (payload != null && payload.length != 0) { + // the generated artifacts were already decoded by the handler + decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload); + if (decodedPayload.length == 0) { + log.debug("Failed to decode the payload."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + + String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload); + artifactInfo.setArtifactChecksum(checkSum); + log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum); + + // Specific payload validations of different types + Either isValidPayload = Either.left(true); + if (isDeploymentArtifact(artifactInfo)) { + log.trace("Starting deployment artifacts payload validation"); + String artifactType = artifactInfo.getArtifactType(); + if (ArtifactTypeEnum.HEAT.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { + isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType); + if (isValidPayload.isLeft()) { + isValidPayload = extractHeatParameters(artifactInfo); + } + } + else if (ArtifactTypeEnum.YANG_XML.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.VENDOR_LICENSE.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION + .getType() + .equalsIgnoreCase(artifactType)) { + isValidPayload = validateXmlPayload(decodedPayload, artifactType); + } + else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA + .getType() + .equalsIgnoreCase(artifactType) + || ArtifactTypeEnum.VES_EVENTS.getType() + .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS + .getType() + .equalsIgnoreCase(artifactType)) { + String artifactFileName = artifactInfo.getArtifactName(); + String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase(); + switch (fileExtension) { + case "xml": + isValidPayload = validateXmlPayload(decodedPayload, artifactType); + break; + case "json": + isValidPayload = validateJsonPayload(decodedPayload, artifactType); + break; + case "yml": + case "yaml": + isValidPayload = validateYmlPayload(decodedPayload, artifactType); + break; + default: + break; + } + } + } + if (isValidPayload.isRight()) { + ResponseFormat responseFormat = isValidPayload.right().value(); + return Either.right(responseFormat); + } + + } // null/empty payload is normal if called from metadata update ONLY. + // The validation of whether this is metadata/payload update case is + // currently done separately + else { + if (!isArtifactMetadataUpdate) { + log.debug("Payload is missing."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + return Either.right(responseFormat); + } + } + log.trace("Ended payload handling"); + return Either.left(decodedPayload); + } + + private Either validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) { + // Basic YAML validation + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { + log.debug("Invalid YAML format"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); + return Either.right(responseFormat); + } + if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) { + // HEAT specific YAML validation + DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class); + if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) { + log.debug("HEAT doesn't contain required \"heat_template_version\" section."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType); + return Either.right(responseFormat); + } + } + + return Either.left(true); + } + + private Either validateYmlPayload(byte[] decodedPayload, String artifactType) { + Either res = Either.left(true); + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + if (!yamlToObjectConverter.isValidYaml(decodedPayload)) { + log.debug("Invalid YAML format"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType); + res = Either.right(responseFormat); + } + + return res; + } + + private Either validateXmlPayload(byte[] payload, String artifactType) { + boolean isXmlValid = isValidXml(payload); + if (!isXmlValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_XML, artifactType); + log.debug("Invalid XML content"); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either validateJsonPayload(byte[] payload, String type) { + boolean isJsonValid = isValidJson(payload); + if (!isJsonValid) { + ResponseFormat responseFormat = ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.INVALID_JSON, type); + log.debug("Invalid JSON content"); + return Either.right(responseFormat); + } + return Either.left(true); + } + + public Either deleteArtifactByInterface(String resourceId, String userUserId, String artifactId, + boolean inTransaction) { + User user = new User(); + user.setUserId(userUserId); + Either parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata); + if (parent.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent + .right() + .value())); + return Either.right(responseFormat); + } + Either, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent + .left() + .value(), + false, inTransaction); + if (handleDelete.isRight()) { + return Either.right(handleDelete.right().value()); + } + Either result = handleDelete.left().value(); + return Either.left(result.right().value()); + + } + + private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) { + Operation op = new Operation(); + long time = System.currentTimeMillis(); + op.setCreationDate(time); + + String artifactName = artifactInfo.getArtifactName(); + artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName)); + + op.setImplementation(artifactInfo); + op.setLastUpdateDate(time); + return op; + } + + private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) { + String newArtifactName = operationName + "_" + artifactName; + log.trace("converting artifact name {} to {}", artifactName, newArtifactName); + return newArtifactName; + } + + // download by MSO + public Either downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) { + + // General validation + if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + artifactName = ValidationUtils.normalizeFileName(artifactName); + + // Resource validation + Either validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); + if (validateResourceNameAndVersion.isRight()) { + return Either.right(validateResourceNameAndVersion.right().value()); + } + + Resource resource = validateResourceNameAndVersion.left().value(); + String resourceId = resource.getUniqueId(); + + // Service validation + Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + Map artifacts = resource.getDeploymentArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + log.debug("Deployment artifacts of resource {} are not found", resourceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + ArtifactDefinition deploymentArtifact = null; + + for (ArtifactDefinition artifactDefinition : artifacts.values()) { + if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName() + .equals(artifactName)) { + log.debug("Found deployment artifact {}", artifactName); + deploymentArtifact = artifactDefinition; + break; + } + } + + if (deploymentArtifact == null) { + log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + // Downloading the artifact + Either, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact); + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", artifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + // download by MSO + public Either downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) { + + // General validation + if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + artifactName = ValidationUtils.normalizeFileName(artifactName); + + // Service validation + Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + Service service = validateServiceNameAndVersion.left().value(); + + // ResourceInstance validation + Either validateResourceInstance = validateResourceInstance(service, resourceInstanceName); + if (validateResourceInstance.isRight()) { + return Either.right(validateResourceInstance.right().value()); + } + + ComponentInstance resourceInstance = validateResourceInstance.left().value(); + + Map artifacts = resourceInstance.getDeploymentArtifacts(); + + final String finalArtifactName = artifactName; + Predicate filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName); + + boolean hasDeploymentArtifacts = artifacts != null && artifacts.values() + .stream() + .anyMatch(filterArtifactByName); + ArtifactDefinition deployableArtifact; + + if (!hasDeploymentArtifacts) { + log.debug("Deployment artifact with name {} not found", artifactName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); + } + + log.debug("Found deployment artifact {}", artifactName); + deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get(); + // Downloading the artifact + Either, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact); + + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", artifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + private Either validateResourceInstance(Service service, String resourceInstanceName) { + + List riList = service.getComponentInstances(); + for (ComponentInstance ri : riList) { + if (ri.getNormalizedName().equals(resourceInstanceName)) { + return Either.left(ri); + } + } + + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName)); + } + + private Either validateServiceNameAndVersion(String serviceName, String serviceVersion) { + + Either, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName); + if (serviceListBySystemName.isRight()) { + log.debug("Couldn't fetch any service with name {}", serviceName); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName + .right() + .value(), ComponentTypeEnum.SERVICE), serviceName)); + } + List serviceList = serviceListBySystemName.left().value(); + if (serviceList == null || serviceList.isEmpty()) { + log.debug("Couldn't fetch any service with name {}", serviceName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName)); + } + + Service foundService = null; + for (Service service : serviceList) { + if (service.getVersion().equals(serviceVersion)) { + log.trace("Found service with version {}", serviceVersion); + foundService = service; + break; + } + } + + if (foundService == null) { + log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE + .getValue(), serviceVersion)); + } + return Either.left(foundService); + } + + private Either validateResourceNameAndVersion(String resourceName, String resourceVersion) { + + Either resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata); + if (resourceListBySystemName.isRight()) { + log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName + .right() + .value()), resourceName)); + } + return Either.left(resourceListBySystemName.left().value()); + } + + public Either downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) { + // Validation + log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName); + if (serviceName == null || serviceVersion == null || artifactName == null) { + log.debug("One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + // Normalizing artifact name + final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName); + + // Service validation + Either validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion); + if (validateServiceNameAndVersion.isRight()) { + return Either.right(validateServiceNameAndVersion.right().value()); + } + + String serviceId = validateServiceNameAndVersion.left().value().getUniqueId(); + + // Looking for deployment or tosca artifacts + Service service = validateServiceNameAndVersion.left().value(); + + if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) { + log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + } + + Optional foundArtifactOptl = null; + + if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) { + foundArtifactOptl = service.getDeploymentArtifacts().values().stream() + // filters artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + } + if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) { + foundArtifactOptl = service.getToscaArtifacts().values().stream() + // filters TOSCA artifact by name + .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny(); + } + if (!foundArtifactOptl.isPresent()) { + log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName)); + } + log.debug("Found deployment artifact {}", normalizedArtifactName); + // Downloading the artifact + Either, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl + .get()); + if (downloadArtifactEither.isRight()) { + log.debug("Download artifact {} failed", normalizedArtifactName); + return Either.right(downloadArtifactEither.right().value()); + } + log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId()); + return Either.left(downloadArtifactEither.left().value().getRight()); + } + + public Either, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) { + log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId); + Either artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId); + if (artifactById.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value()); + log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, "")); + } + ArtifactDefinition artifactDefinition = artifactById.left().value(); + if (artifactDefinition == null) { + log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "")); + } + + return downloadArtifact(artifactDefinition); + } + + private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) { + boolean found = false; + Map artifactsS = component.getArtifacts(); + if (artifactsS != null) { + for (Map.Entry entry : artifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + Map deploymentArtifactsS = component.getDeploymentArtifacts(); + if (!found && deploymentArtifactsS != null) { + for (Map.Entry entry : deploymentArtifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + Map toscaArtifactsS = component.getToscaArtifacts(); + if (!found && toscaArtifactsS != null) { + for (Map.Entry entry : toscaArtifactsS.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + switch (component.getComponentType()) { + case RESOURCE: + Map interfaces = ((Resource) component).getInterfaces(); + if (!found && interfaces != null) { + for (Map.Entry entry : interfaces.entrySet()) { + Map operations = entry.getValue().getOperationsMap(); + for (Map.Entry entryOp : operations.entrySet()) { + if (entryOp.getValue().getImplementation() != null && entryOp.getValue() + .getImplementation() + .getUniqueId() + .equals(artifactId)) { + found = true; + break; + } + } + } + } + break; + case SERVICE: + Map apiArtifacts = ((Service) component).getServiceApiArtifacts(); + if (!found && apiArtifacts != null) { + for (Map.Entry entry : apiArtifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + break; + default: + + } + + return found; + } + + private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) { + + boolean found = false; + List resourceInstances = component.getComponentInstances(); + ComponentInstance resourceInstance = null; + for (ComponentInstance ri : resourceInstances) { + if (ri.getUniqueId().equals(resourceInstanceId)) { + resourceInstance = ri; + break; + } + } + if (resourceInstance != null) { + Map artifacts = resourceInstance.getDeploymentArtifacts(); + if (artifacts != null) { + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + if (!found) { + artifacts = resourceInstance.getArtifacts(); + if (artifacts != null) { + for (Map.Entry entry : artifacts.entrySet()) { + if (entry.getValue().getUniqueId().equals(artifactId)) { + found = true; + break; + } + } + } + } + } + return found; + } + + private Either validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType, + String containerComponentType) { + + ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType); + componentForAudit.getNodeType(); + + Either componentResult = toscaOperationFacade + .getToscaFullElement(componentId); + + if (componentResult.isRight()) { + ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId); + log.debug("Service not found, serviceId {}", componentId); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null); + return Either.right(responseFormat); + } + return Either.left(componentResult.left().value()); + } + + private Either validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) { + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) { + Either canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + String uniqueId = component.getUniqueId(); + log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId); + handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right() + .value(), component + .getComponentType(), null); + return Either.right(canWork.right().value()); + } + } + return Either.left(true); + } + + private Either validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) { + + if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) { + String role = user.getRole(); + if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + return Either.left(true); + } + + private Either validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) { + Either validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction); + + if (validateUserExists.isRight()) { + User user = new User(); + user.setUserId(userId); + handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right() + .value(), componentType, null); + return Either.right(validateUserExists.right().value()); + } + return Either.left(validateUserExists.left().value()); + } + + protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) { + AuditingActionEnum auditingAction = null; + switch (operation.getArtifactOperationEnum()) { + case CREATE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD; + break; + case UPDATE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE; + break; + case DELETE: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE; + break; + case DOWNLOAD: + auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD; + break; + default: + break; + } + return auditingAction; + } + + private Either, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) { + String esArtifactId = artifactDefinition.getEsId(); + Either artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactfromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {}", actionStatus); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition + .getArtifactDisplayName()); + + return Either.right(responseFormat); + } + + ESArtifactData esArtifactData = artifactfromES.left().value(); + byte[] data = esArtifactData.getDataAsArray(); + if (data == null) { + log.debug("Artifact data from ES is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName())); + } + String artifactName = artifactDefinition.getArtifactName(); + log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName); + return Either.left(new ImmutablePair(artifactName, data)); + } + + public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) { + return new ESArtifactData(artifactInfo.getEsId(), artifactPayload); + } + + private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) { + CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData); + + if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) { + log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId); + } + else { + log.info("Failed to save artifact {}.", artifactData.getId()); + return false; + } + return true; + } + + private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) { + return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE); + } + + private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) { + return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()); + } + + public Either createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) { + Either user = userAdminManager.getUser(userUserId, inTransaction); + if (user.isRight()) { + ResponseFormat responseFormat; + if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("create artifact placeholder - not authorized user, userId {}", userUserId); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } + else { + log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId); + responseFormat = componentsUtils.getResponseFormat(user.right().value()); + } + return Either.right(responseFormat); + } + + ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user + .left() + .value(), groupType); + return Either.left(artifactDefinition); + } + + public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); + String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE); + String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); + + artifactInfo.setArtifactDisplayName(artifactName); + artifactInfo.setArtifactLabel(logicalName.toLowerCase()); + artifactInfo.setArtifactType(artifactType); + artifactInfo.setDescription(artifactDescription); + artifactInfo.setArtifactGroupType(groupType); + nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo); + + setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo); + + return artifactInfo; + } + + private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) { + String uniqueId = null; + + if (resourceId != null) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel() + .toLowerCase()); + artifactInfo.setUniqueId(uniqueId); + } + artifactInfo.setUserIdCreator(user.getUserId()); + String fullName = user.getFullName(); + artifactInfo.setUpdaterFullName(fullName); + + long time = System.currentTimeMillis(); + + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + artifactInfo.setMandatory(true); + } + + public Either, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { + return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId); + } + + public Either addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) { + return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId); + } + + private Either createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) { + + byte[] payload = payloadStr.getBytes(); + + ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload); + return Either.left(artifactData); + } + + /** + * @param artifactDefinition + * @return + */ + public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + String instanceId, boolean shouldLock, boolean inTransaction) { + String payload = generateHeatEnvPayload(artifactDefinition); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } + + public Either forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, boolean inTransaction, String instanceId) { + String payload = generateHeatEnvPayload(artifactDefinition); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction) + .left() + .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef)); + } + + private Either updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) { + if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) { + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + Optional findFirst = componentInstances.stream() + .filter(ci -> ci.getUniqueId() + .equals(instanceId)) + .findFirst(); + if (findFirst.isPresent()) { + ComponentInstance relevantInst = findFirst.get(); + List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst + .getGroupInstances()); + + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + updatedGroupInstances.forEach(gi -> { + gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); + gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils + .convertFromStorageResponse(status.right() + .value()), clonedBeforeGenerate.getArtifactDisplayName()); + return Either.right(responseFormat); + } + } + } + } + } + return Either.left(updatedArtDef); + } + + private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { + List heatParameters = artifactDefinition.getListHeatParameters(); + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append("parameters:\n"); + if (heatParameters != null) { + heatParameters.sort(Comparator.comparing(e -> e.getName())); + + List empltyHeatValues = new ArrayList<>(); + + for (HeatParameterDefinition heatParameterDefinition : heatParameters) { + + String heatValue = heatParameterDefinition.getCurrentValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + heatValue = heatParameterDefinition.getDefaultValue(); + if (!ValidationUtils.validateStringNotEmpty(heatValue)) { + empltyHeatValues.add(heatParameterDefinition); + continue; + } + } + HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType()); + if (type != null) { + switch (type) { + case BOOLEAN: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(Boolean.parseBoolean(heatValue)) + .append("\n"); + break; + case NUMBER: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(new BigDecimal(heatValue).toPlainString()) + .append("\n"); + break; + case COMMA_DELIMITED_LIST: + case JSON: + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(heatValue) + .append("\n"); + break; + default: + String value = heatValue; + boolean starts = value.startsWith("\""); + boolean ends = value.endsWith("\""); + if (!(starts && ends)) { + starts = value.startsWith("'"); + ends = value.endsWith("'"); + if (!(starts && ends)) { + value = "\"" + value + "\""; + } + } + sb.append(" ") + .append(heatParameterDefinition.getName()) + .append(":") + .append(" ") + .append(value); + sb.append("\n"); + break; + + } + } + } + if (!empltyHeatValues.isEmpty()) { + empltyHeatValues.sort(Comparator.comparing(e -> e.getName())); + empltyHeatValues.forEach(hv -> { + sb.append(" ").append(hv.getName()).append(":"); + HeatParameterType type = HeatParameterType.isValidType(hv.getType()); + if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv + .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) { + sb.append(" \"\"").append("\n"); + } + else { + sb.append(" ").append("\n"); + } + }); + } + } + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + + // DE265919 fix + return sb.toString().replaceAll("\\\\n", "\n"); + } + + /** + * @param artifactDefinition + * @param payload + * @return + */ + public Either generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition + .getHeatParamsUpdateDate(), + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); + + } + + public Either forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, + User modifier, String instanceId, boolean shouldLock, boolean inTransaction) { + return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis, + () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId); + + } + + protected Either generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, + boolean shouldLock, boolean inTransaction, Supplier payloadUpdateDateGen, Supplier> esDataCreator, String instanceId) { + + log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition + .getEsId()); + if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition + .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) { + + log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId()); + Either artifactDataRes = esDataCreator.get(); + ESArtifactData artifactData = null; + + if (artifactDataRes.isLeft()) { + artifactData = artifactDataRes.left().value(); + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(artifactDataRes.right().value()); + } + String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray()); + String oldCheckSum; + String esArtifactId = artifactDefinition.getEsId(); + Either artifactfromES; + ESArtifactData esArtifactData; + if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) { + log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId); + artifactfromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactfromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName())); + } + esArtifactData = artifactfromES.left().value(); + oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray()); + } + else { + oldCheckSum = artifactDefinition.getArtifactChecksum(); + + } + Either updateArifactDefinitionStatus = null; + + if (shouldLock) { + Either lockComponent = lockComponent(component, "Update Artifact - lock resource: "); + if (lockComponent.isRight()) { + handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition + .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null); + return Either.right(lockComponent.right().value()); + } + } + try { + if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) { + + artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get()); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component + .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition + .getArtifactType(), artifactDefinition.getEsId()); + if (updateArifactDefinitionStatus.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus + .right() + .value()), artifactDefinition.getArtifactDisplayName()); + log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId()); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + } + } + else { + + oldCheckSum = artifactDefinition.getArtifactChecksum(); + artifactDefinition.setArtifactChecksum(newCheckSum); + artifactDefinition.setEsId(artifactDefinition.getUniqueId()); + log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition + .getArtifactType(), artifactDefinition.getEsId()); + updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component + .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); + + log.trace("Update Payload ", artifactDefinition.getEsId()); + } + if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { + + artifactDefinition = updateArifactDefinitionStatus.left().value(); + artifactData.setId(artifactDefinition.getUniqueId()); + CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); + + if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) { + if (!inTransaction) { + titanDao.commit(); + } + log.debug("Artifact Saved In ES {}", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + } + else { + if (!inTransaction) { + titanDao.rollback(); + } + log.info("Failed to save artifact {}.", artifactData.getId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + } + } + else { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus + .right() + .value()), artifactDefinition.getArtifactDisplayName()); + log.debug("Failed To update artifact {}", artifactData.getId()); + handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition + .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, + ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName); + + return Either.right(responseFormat); + + } + } + finally { + if (shouldLock) { + graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType() + .getNodeType()); + } + } + } + + return Either.left(artifactDefinition); + } + + + public Map buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List updatedRequiredArtifacts) { + return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef + .getArtifactLabel(), artifactDef.getArtifactDisplayName(), + artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters()); + + } + + public Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent, + List updatedRequiredArtifacts, List heatParameters) { + + Map json = new HashMap(); + if (artifactId != null && !artifactId.isEmpty()) { + json.put(Constants.ARTIFACT_ID, artifactId); + } + + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_TYPE, artifactType); + json.put(Constants.ARTIFACT_DESCRIPTION, description); + + if (artifactContent != null) { + log.debug("payload is encoded. perform decode"); + String encodedPayload = Base64.encodeBase64String(artifactContent); + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + } + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); + json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() + : updatedRequiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e + .getType() + .equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()) + .collect(Collectors.toList())); + json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() + : heatParameters); + return json; + } + + public Either, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) { + + String jsonStr = gson.toJson(json); + ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo; + String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); + Either, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId, + artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true); + if (uploadArtifactToService.isRight()) { + return Either.right(uploadArtifactToService.right().value()); + } + + return Either.left(uploadArtifactToService.left().value()); + } + + private Either, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, + org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + convertParentType(componentType); + String parentId = parent.getUniqueId(); + ArtifactDefinition currArtifact = artifactInfo; + + if (origMd5 != null) { + Either validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation); + if (validateMd5.isRight()) { + ResponseFormat responseFormat = validateMd5.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) { + Either deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance); + if (deploymentValidationResult.isRight()) { + ResponseFormat responseFormat = deploymentValidationResult.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + + Either payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction)); + if (payloadEither.isRight()) { + ResponseFormat responseFormat = payloadEither.right().value(); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + else { // duplicate + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD); + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null); + return Either.right(responseFormat); + } + } + + // lock resource + if (shouldLock) { + Either lockComponent = lockComponent(parent, "Update Artifact - lock "); + if (lockComponent.isRight()) { + handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right() + .value(), componentType, null); + return Either.right(lockComponent.right().value()); + } + } + Either, ResponseFormat> resultOp = null; + try { + resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5); + return resultOp; + + } + finally { + // unlock resource + if (resultOp == null || resultOp.isRight()) { + log.debug("all changes rollback"); + if (!inTransaction) { + titanDao.rollback(); + } + } + else { + log.debug("all changes committed"); + if (!inTransaction) { + titanDao.commit(); + } + } + if (shouldLock) { + componentType = parent.getComponentType(); + } + NodeTypeEnum nodeType = componentType.getNodeType(); + graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType); + } + } + + private Either, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, String origMd5) { + + Either, ResponseFormat> resultOp = null; + Either insideEither = null; + Either getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user); + if (getRI.isRight()) { + return Either.right(getRI.right().value()); + } + ComponentInstance ri = getRI.left().value(); + Either getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user); + if (getArtifactRes.isRight()) { + return Either.right(getArtifactRes.right().value()); + } + ArtifactDefinition currArtifact = getArtifactRes.left().value(); + + if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType() + .equals(ArtifactTypeEnum.HEAT_VOL + .getType()) || currArtifact + .getArtifactType() + .equals(ArtifactTypeEnum.HEAT_NET.getType())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + List currentHeatEnvParams = currArtifact.getListHeatParameters(); + List updatedHeatEnvParams = artifactInfo.getListHeatParameters(); + new ArrayList(); + + // upload + if (origMd5 != null) { + Either, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri + .getName(), currentHeatEnvParams, + updatedHeatEnvParams, currArtifact.getArtifactName()); + if (uploadParamsValidationResult.isRight()) { + ResponseFormat responseFormat = uploadParamsValidationResult.right().value(); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + artifactInfo.setListHeatParameters(updatedHeatEnvParams); + } + + Either validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV + .getType()); + if (validateAndConvertHeatParamers.isRight()) { + ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value(); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) { + // fill reduced heat env parameters List for updating + replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams); + currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis()); + currArtifact.setListHeatParameters(currentHeatEnvParams); + + Either updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent + .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId); + if (updateArifactRes.isRight()) { + log.debug("Failed to update artifact on graph - {}", artifactId); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes + .right() + .value())); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left() + .value() + .getUniqueId(), parent.getUniqueId()); + if (error != StorageOperationStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error)); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri + .getName()); + return Either.right(responseFormat); + } + + } + insideEither = Either.left(currArtifact); + resultOp = Either.left(insideEither); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri + .getName()); + return resultOp; + } + + private void replaceCurrHeatValueWithUpdatedValue(List currentHeatEnvParams, List updatedHeatEnvParams) { + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + String paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + String updatedParamValue = heatEnvParam.getCurrentValue(); + currHeatParam.setCurrentValue(updatedParamValue); + } + } + } + } + + private Either, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent, + ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) { + + Either, ResponseFormat> resultOp; + Either insideEither = null; + String currentHeatId = currHeatArtifact.getUniqueId(); + + String esArtifactId = currHeatArtifact.getEsId(); + Either artifactFromES = artifactCassandraDao.getArtifact(esArtifactId); + if (artifactFromES.isRight()) { + CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value(); + StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse); + log.debug("Error when getting artifact from ES, error: {}", actionStatus); + return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName())); + } + + ESArtifactData esArtifactData = artifactFromES.left().value(); + + ArtifactDefinition updatedHeatArt = currHeatArtifact; + + List updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters(); + List currentHeatEnvParams = currHeatArtifact.getListHeatParameters(); + List newHeatEnvParams = new ArrayList(); + + if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams + .isEmpty()) { + + String paramName; + for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { + + paramName = heatEnvParam.getName(); + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + String updatedParamValue = heatEnvParam.getCurrentValue(); + if (updatedParamValue == null) { + updatedParamValue = heatEnvParam.getDefaultValue(); + } + HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); + if (!paramType.getValidator().isValid(updatedParamValue, null)) { + ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; + ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV + .getType(), paramType.getType(), paramName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, ""); + return Either.right(responseFormat); + + } + currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); + newHeatEnvParams.add(currHeatParam); + break; + } + } + } + if (!newHeatEnvParams.isEmpty()) { + currHeatArtifact.setListHeatParameters(currentHeatEnvParams); + Either operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent + .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId); + + if (operationStatus.isRight()) { + log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId()); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus + .right() + .value())); + return Either.right(responseFormat); + + } + updatedHeatArt = operationStatus.left().value(); + boolean res = true; + if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) { + esArtifactData.setId(updatedHeatArt.getEsId()); + } + res = saveArtifacts(esArtifactData, parent.getUniqueId()); + + if (res) { + log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt + .getUniqueId(), responseFormat, componentType, null); + } + else { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact"); + log.debug("Failed to save the artifact."); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt + .getUniqueId(), responseFormat, componentType, null); + resultOp = Either.right(responseFormat); + } + + insideEither = Either.left(updatedHeatArt); + } + } + Either updateHeatEnvArtifact; + if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) { + artifactEnvInfo.setArtifactChecksum(null); + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt + .getUniqueId(), componentType.getNodeType(), componentId); + } + else { + updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType + .getNodeType()); + + } + if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) { + ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact + .left() + .value(), parent, componentType); + if (result != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(result); + return Either.right(responseFormat); + } + } + + if (updatedHeatEnvParams.isEmpty()) { + return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType); + } + resultOp = Either.left(insideEither); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); + return resultOp; + + } + + private Either, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName()); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, ""); + return Either.right(responseFormat); + } + + + private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) { + StorageOperationStatus error = StorageOperationStatus.OK; + log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId()); + List groupsInstances = ri.getGroupInstances(); + List groupInstancesId = null; + if (groupsInstances != null && !groupsInstances.isEmpty()) { + groupInstancesId = groupsInstances.stream() + .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts() + .contains(artifactId)) + .map(GroupInstanceDataDefinition::getUniqueId) + .collect(Collectors.toList()); + } + if (groupInstancesId != null && !groupInstancesId.isEmpty()) { + toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId); + } + return error; + + } + + public Either, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType, + String riName, List currentHeatEnvParams, List updatedHeatEnvParams, String currArtifactName) { + + if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo + .getArtifactName(), currArtifactName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); + return Either.right(responseFormat); + } + + for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) { + String paramName = uploadedHeatParam.getName(); + boolean isExistsInHeat = false; + for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { + if (paramName.equalsIgnoreCase(currHeatParam.getName())) { + + isExistsInHeat = true; + uploadedHeatParam.setType(currHeatParam.getType()); + uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue()); + uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue()); + uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId()); + break; + } + } + if (!isExistsInHeat) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName); + handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName); + return Either.right(responseFormat); + } + } + return Either.left(updatedHeatEnvParams); + } + + private Either getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { + ResponseFormat responseFormat = null; + List ris = component.getComponentInstances(); + for (ComponentInstance ri : ris) { + if (riID.equals(ri.getUniqueId())) { + return Either.left(ri); + } + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID); + log.debug("Resource Instance not found, resourceInstanceId {}", riID); + handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null); + return Either.right(responseFormat); + } + + private Either getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) { + ResponseFormat responseFormat = null; + Map rtifactsMap = ri.getDeploymentArtifacts(); + for (ArtifactDefinition artifact : rtifactsMap.values()) { + if (artifactId.equals(artifact.getUniqueId())) { + return Either.left(artifact); + } + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId()); + handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri + .getName()); + return Either.right(responseFormat); + } + + public ArtifactDefinition extractArtifactDefinition(Either eitherArtifact) { + ArtifactDefinition ret; + if (eitherArtifact.isLeft()) { + ret = eitherArtifact.left().value(); + } + else { + ret = eitherArtifact.right().value().getImplementationArtifact(); + } + return ret; + } + + /** + * downloads artifact of component by UUIDs + * + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param auditAdditionalParam + * @return + */ + public Either downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map auditAdditionalParam) { + Wrapper errorWrapper = new Wrapper<>(); + Either result; + byte[] downloadedArtifact = null; + Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName()); + } + if (errorWrapper.isEmpty()) { + result = Either.left(downloadedArtifact); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + /** + * downloads an artifact of resource instance of component by UUIDs + * + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param auditAdditionalParam + * @return + */ + public Either downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map auditAdditionalParam) { + Wrapper errorWrapper = new Wrapper<>(); + Either result; + byte[] downloadedArtifact = null; + ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + if (errorWrapper.isEmpty()) { + downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance + .getName()); + } + if (errorWrapper.isEmpty()) { + result = Either.left(downloadedArtifact); + } + else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + /** + * uploads an artifact to a component by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param additionalParams + * @param operation + * @return + */ + public Either uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map additionalParams, + ArtifactOperationInfo operation) { + Wrapper errorWrapper = new Wrapper<>(); + Either, ResponseFormat> actionResult = null; + Either uploadArtifactResult; + ArtifactDefinition uploadArtifact = null; + Component component = null; + String componentId = null; + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + uploadArtifact = actionResult.left().value().left().value(); + uploadArtifactResult = Either.left(uploadArtifact); + } + else { + uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); + return uploadArtifactResult; + } + + /** + * upload an artifact to a resource instance by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param additionalParams + * @param operation + * @return + */ + public Either uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, + Map additionalParams, ArtifactOperationInfo operation) { + Wrapper errorWrapper = new Wrapper<>(); + Either uploadArtifactResult; + Either, ResponseFormat> actionResult = null; + ArtifactDefinition uploadArtifact = null; + Component component = null; + String componentInstanceId; + String componentId; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ImmutablePair componentRiPair = null; + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName)); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + uploadArtifact = actionResult.left().value().left().value(); + uploadArtifactResult = Either.left(uploadArtifact); + } + else { + uploadArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact); + return uploadArtifactResult; + } + + /** + * updates an artifact on a component by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, + Map additionalParams, ArtifactOperationInfo operation) { + Wrapper errorWrapper = new Wrapper<>(); + Either updateArtifactResult; + Either, ResponseFormat> actionResult = null; + ArtifactDefinition updateArtifact = null; + Component component = null; + String componentId = null; + String artifactId = null; + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + updateArtifact = actionResult.left().value().left().value(); + updateArtifactResult = Either.left(updateArtifact); + + } + else { + updateArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); + return updateArtifactResult; + } + + /** + * updates an artifact on a resource instance by UUID + * + * @param data + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, + Map additionalParams, ArtifactOperationInfo operation) { + + Wrapper errorWrapper = new Wrapper<>(); + Either updateArtifactResult; + Either, ResponseFormat> actionResult = null; + ArtifactDefinition updateArtifact = null; + Component component = null; + String componentInstanceId = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ImmutablePair componentRiPair = null; + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); + } + if (errorWrapper.isEmpty()) { + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + updateArtifact = actionResult.left().value().left().value(); + updateArtifactResult = Either.left(updateArtifact); + } + else { + updateArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact); + return updateArtifactResult; + } + + /** + * deletes an artifact on a component by UUID + * + * @param request + * @param componentType + * @param componentUuid + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map additionalParams, + ArtifactOperationInfo operation) { + + Wrapper errorWrapper = new Wrapper<>(); + Either deleteArtifactResult; + Either, ResponseFormat> actionResult = null; + ArtifactDefinition deleteArtifact = null; + Component component = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid)); + } + if (errorWrapper.isEmpty()) { + componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(); + String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName(); + if (!getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, componentId, userId, errorWrapper); + if (component != null) { + componentId = component.getUniqueId(); + componentName = component.getName(); + } + } + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName); + } + if (errorWrapper.isEmpty()) { + artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType); + } + if (errorWrapper.isEmpty()) { + actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + deleteArtifact = actionResult.left().value().left().value(); + deleteArtifactResult = Either.left(deleteArtifact); + } + else { + deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); + return deleteArtifactResult; + } + + /** + * deletes an artifact from a resource instance by UUID + * + * @param request + * @param componentType + * @param componentUuid + * @param resourceInstanceName + * @param artifactUUID + * @param additionalParams + * @param operation TODO + * @return + */ + public Either deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, + Map additionalParams, ArtifactOperationInfo operation) { + + Wrapper errorWrapper = new Wrapper<>(); + Either deleteArtifactResult; + Either, ResponseFormat> actionResult = null; + ArtifactDefinition deleteArtifact = null; + Component component = null; + String componentInstanceId = null; + String componentId = null; + String artifactId = null; + String origMd5 = request.getHeader(Constants.MD5_HEADER); + String userId = request.getHeader(Constants.USER_ID_HEADER); + ImmutablePair componentRiPair = null; + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (errorWrapper.isEmpty() && !getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + component = checkoutParentComponent(componentType, getComponentRes.left() + .value() + .getMetadataDataDefinition() + .getUniqueId(), userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + if (component == null) { + componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper); + } + else { + componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper); + } + } + if (errorWrapper.isEmpty()) { + componentInstanceId = componentRiPair.getRight().getUniqueId(); + componentId = componentRiPair.getLeft().getUniqueId(); + artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper); + } + if (errorWrapper.isEmpty()) { + + actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum + .findParamByType(componentType)); + + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult + .right() + .value()); + errorWrapper.setInnerElement(actionResult.right().value()); + } + } + if (errorWrapper.isEmpty()) { + deleteArtifact = actionResult.left().value().left().value(); + deleteArtifactResult = Either.left(deleteArtifact); + } + else { + deleteArtifactResult = Either.right(errorWrapper.getInnerElement()); + } + updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact); + return deleteArtifactResult; + } + + private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper errorWrapper) { + String artifactId = null; + ArtifactDefinition foundArtifact = null; + if (instance.getDeploymentArtifacts() != null) { + foundArtifact = instance.getDeploymentArtifacts() + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); + } + if (foundArtifact == null && instance.getArtifacts() != null) { + foundArtifact = instance.getArtifacts() + .values() + .stream() + .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID() + .equals(artifactUUID)) + .findFirst() + .orElse(null); + } + if (foundArtifact == null) { + log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId()); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + } + else { + artifactId = foundArtifact.getUniqueId(); + } + return artifactId; + } + + @SuppressWarnings("unchecked") + public Either createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component, + Map existingEnvVersions) { + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getDeploymentResourceInstanceArtifacts(); + if (deploymentResourceArtifacts == null) { + log.debug("no deployment artifacts are configured for generated artifacts"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + Map placeHolderData = (Map) deploymentResourceArtifacts.get(envType); + if (placeHolderData == null) { + log.debug("no env type {} are configured for generated artifacts", envType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + Either createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user + .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true); + if (createArtifactPlaceHolder.isRight()) { + return Either.right(createArtifactPlaceHolder.right().value()); + } + ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value(); + artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId()); + artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis()); + artifactHeatEnv.setTimeout(0); + buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData); + // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow + handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions); + ArtifactDefinition heatEnvPlaceholder; + // Evg : for resource instance artifact will be added later as block with other env artifacts from BL + if (parentType != NodeTypeEnum.ResourceInstance) { + Either addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component + .getUniqueId(), parentType, parentId); + if (addHeatEnvArtifact.isRight()) { + log.debug("failed to create heat env artifact on resource instance"); + return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact + .right() + .value(), false), "", null)); + } + heatEnvPlaceholder = createArtifactPlaceHolder.left().value(); + } + else { + heatEnvPlaceholder = artifactHeatEnv; + artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion()); + setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder); + } + String artifactData = buildAuditingArtifactData(heatEnvPlaceholder); + ComponentTypeEnum componentType = component.getComponentType(); + if (parentType == NodeTypeEnum.ResourceInstance) { + componentType = ComponentTypeEnum.RESOURCE_INSTANCE; + } + componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType, + ResourceAuditData.newBuilder().build(), + ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), + parentName, null, artifactData, null); + return Either.left(heatEnvPlaceholder); + } + + private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) { + if (artifact.getListHeatParameters() == null) { + return; + } + List heatEnvParameters = new ArrayList<>(); + for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) { + HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter); + heatEnvParameter.setDefaultValue(parameter.getCurrentValue()); + heatEnvParameter.setCurrentValue(null); + heatEnvParameters.add(heatEnvParameter); + } + artifactDefinition.setListHeatParameters(heatEnvParameters); + } + + private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map placeHolderData) { + String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); + String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); + String name = heatArtifact.getArtifactName(); + String fileName; + if (name == null) { + name = heatArtifact.getArtifactLabel(); + fileName = name + "." + envExtension; + } + else { + fileName = name.replaceAll("." + heatExtension, "." + envExtension); + } + heatEnvArtifact.setArtifactName(fileName); + } + + private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map existingEnvVersions) { + if (null != existingEnvVersions) { + String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); + if (null != prevVersion) { + heatEnvArtifact.setArtifactVersion(prevVersion); + } + } + } + + /** + * Handles Artifacts Request For Inner Component + * + * @param artifactsToHandle + * @param component + * @param user + * @param vfcsNewCreatedArtifacts + * @param operation + * @param shouldLock + * @param inTransaction + * @return + */ + public Either, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List artifactsToHandle, Resource component, User user, List vfcsNewCreatedArtifacts, + ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { + + Either, ResponseFormat> handleArtifactsResult = null; + ComponentTypeEnum componentType = component.getComponentType(); + List uploadedArtifacts = new ArrayList<>(); + Wrapper errorWrapper = new Wrapper<>(); + Either, ResponseFormat> actionResult; + String originData; + String origMd5; + try { + for (ArtifactDefinition artifact : artifactsToHandle) { + originData = buildJsonStringForCsarVfcArtifact(artifact); + origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData); + actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact + .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); + if (actionResult.isRight()) { + log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component + .getName(), actionResult.right().value()); + errorWrapper.setInnerElement(actionResult.right().value()); + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { + vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); + } + break; + } + uploadedArtifacts.add(actionResult.left().value().left().value()); + } + if (errorWrapper.isEmpty()) { + handleArtifactsResult = Either.left(uploadedArtifacts); + } + else { + handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); + } + } + catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleArtifactsResult = Either.right(responseFormat); + log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); + } + return handleArtifactsResult; + } + + private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper errorWrapper) { + ComponentInstance componentInstance = null; + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); + Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) + .equals(normalizedName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + } + return componentInstance; + } + + private ImmutablePair getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper errorWrapper) { + + ImmutablePair relatedComponentComponentInstancePair = null; + String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); + ComponentInstance componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()) + .equals(normalizedName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + else { + relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); + } + return relatedComponentComponentInstancePair; + } + + private ImmutablePair getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper errorWrapper) { + ComponentInstance componentInstance; + ImmutablePair relatedComponentComponentInstancePair = null; + Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); + if (errorWrapper.isEmpty()) { + componentInstance = component.getComponentInstances() + .stream() + .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)) + .findFirst() + .orElse(null); + if (componentInstance == null) { + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component + .getComponentType() + .getValue(), component.getName())); + log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); + } + else { + relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); + } + } + return relatedComponentComponentInstancePair; + } + + private byte[] downloadArtifact(Map artifacts, String artifactUUID, Wrapper errorWrapper, String componentName) { + + byte[] downloadedArtifact = null; + Either, ResponseFormat> downloadArtifactEither = null; + List artifactsList = null; + ArtifactDefinition deploymentArtifact = null; + if (artifacts != null && !artifacts.isEmpty()) { + artifactsList = artifacts.values() + .stream() + .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); + } + if (artifactsList == null || artifactsList.isEmpty()) { + log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); + } + if (errorWrapper.isEmpty()) { + deploymentArtifact = artifactsList.get(0); + downloadArtifactEither = downloadArtifact(deploymentArtifact); + if (downloadArtifactEither.isRight()) { + log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName()); + errorWrapper.setInnerElement(downloadArtifactEither.right().value()); + } + } + if (errorWrapper.isEmpty()) { + log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); + downloadedArtifact = downloadArtifactEither.left().value().getRight(); + } + return downloadedArtifact; + } + + private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper errorWrapper) { + Component component = null; + Either getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + else { + component = getComponentRes.left().value(); + } + return component; + } + + private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper errorWrapper) { + Component component = null; + Either, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null); + if (getComponentRes.isRight()) { + StorageOperationStatus status = getComponentRes.right().value(); + log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + else { + List value = getComponentRes.left().value(); + if (value.isEmpty()) { + log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid); + ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status)); + } + else { + component = value.get(0); + } + } + return component; + } + + private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper errorWrapper, String parentId, ComponentTypeEnum componentType) { + String artifactId = null; + ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND; + StorageOperationStatus storageStatus; + ArtifactDefinition latestArtifact = null; + List artifacts = null; + Either, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); + if (getArtifactsRes.isRight()) { + storageStatus = getArtifactsRes.right().value(); + log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus); + if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) { + actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); + } + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + if (errorWrapper.isEmpty()) { + artifacts = getArtifactsRes.left() + .value() + .values() + .stream() + .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID() + .equals(artifactUUID)) + .collect(Collectors.toList()); + if (artifacts == null || artifacts.isEmpty()) { + log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + } + if (errorWrapper.isEmpty()) { + latestArtifact = artifacts.stream().max((a1, a2) -> { + int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); + if (compareRes == 0) { + compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2 + .getLastUpdateDate()); + } + return compareRes; + }).get(); + if (latestArtifact == null) { + log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); + } + } + if (errorWrapper.isEmpty()) { + artifactId = latestArtifact.getUniqueId(); + } + return artifactId; + } + + private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper errorWrapper) { + + Component component = null; + Either getUserRes = userBusinessLogic.getUser(userId, false); + if (getUserRes.isRight()) { + log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes + .right() + .value()); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value())); + } + if (errorWrapper.isEmpty()) { + User modifier = getUserRes.left().value(); + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); + Either checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType + .getNodeType(), parentId, checkoutRes.right().value().getStatus()); + errorWrapper.setInnerElement(checkoutRes.right().value()); + } + else { + component = checkoutRes.left().value(); + } + } + return component; + } + + private void updateAuditParametersWithArtifactDefinition(Map additionalParams, ArtifactDefinition artifact) { + if (artifact == null) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ""); + } + } + else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); } - artifactDefinition.setListHeatParameters(heatEnvParameters); - } - - private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map placeHolderData) { - String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName()); - String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION); - String name = heatArtifact.getArtifactName(); - String fileName; - if (name == null) { - name = heatArtifact.getArtifactLabel(); - fileName = name + "." + envExtension; - } else { - fileName = name.replaceAll("." + heatExtension, "." + envExtension); - } - heatEnvArtifact.setArtifactName(fileName); - } - - private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map existingEnvVersions) { - if (null != existingEnvVersions) { - String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName()); - if (null != prevVersion) { - heatEnvArtifact.setArtifactVersion(prevVersion); - } - } - } - - /** - * Handles Artifacts Request For Inner Component - * - * @param artifactsToHandle - * @param component - * @param user - * @param vfcsNewCreatedArtifacts - * @param operation - * @param shouldLock - * @param inTransaction - * @return - */ - public Either, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List artifactsToHandle, Resource component, User user, List vfcsNewCreatedArtifacts, - ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) { - - Either, ResponseFormat> handleArtifactsResult = null; - ComponentTypeEnum componentType = component.getComponentType(); - List uploadedArtifacts = new ArrayList<>(); - Wrapper errorWrapper = new Wrapper<>(); - Either, ResponseFormat> actionResult; - String originData; - String origMd5; - try { - for (ArtifactDefinition artifact : artifactsToHandle) { - originData = buildJsonStringForCsarVfcArtifact(artifact); - origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData); - actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction); - if (actionResult.isRight()) { - log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value()); - errorWrapper.setInnerElement(actionResult.right().value()); - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) { - vfcsNewCreatedArtifacts.addAll(uploadedArtifacts); - } - break; - } - uploadedArtifacts.add(actionResult.left().value().left().value()); - } - if (errorWrapper.isEmpty()) { - handleArtifactsResult = Either.left(uploadedArtifacts); - } else { - handleArtifactsResult = Either.right(errorWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleArtifactsResult = Either.right(responseFormat); - log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e); - } - return handleArtifactsResult; - } - - private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper errorWrapper) { - ComponentInstance componentInstance = null; - String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); - Component component = getComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } - } - return componentInstance; - } - - private ImmutablePair getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper errorWrapper) { - - ImmutablePair relatedComponentComponentInstancePair = null; - String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName); - ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } else { - relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); - } - return relatedComponentComponentInstancePair; - } - - private ImmutablePair getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper errorWrapper) { - ComponentInstance componentInstance; - ImmutablePair relatedComponentComponentInstancePair = null; - Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper); - if (errorWrapper.isEmpty()) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null); - if (componentInstance == null) { - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName())); - log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName()); - } else { - relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance); - } - } - return relatedComponentComponentInstancePair; - } - - private byte[] downloadArtifact(Map artifacts, String artifactUUID, Wrapper errorWrapper, String componentName) { - - byte[] downloadedArtifact = null; - Either, ResponseFormat> downloadArtifactEither = null; - List artifactsList = null; - ArtifactDefinition deploymentArtifact = null; - if (artifacts != null && !artifacts.isEmpty()) { - artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList()); - } - if (artifactsList == null || artifactsList.isEmpty()) { - log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID)); - } - if (errorWrapper.isEmpty()) { - deploymentArtifact = artifactsList.get(0); - downloadArtifactEither = downloadArtifact(deploymentArtifact, null); - if (downloadArtifactEither.isRight()) { - log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName()); - errorWrapper.setInnerElement(downloadArtifactEither.right().value()); - } - } - if (errorWrapper.isEmpty()) { - log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId()); - downloadedArtifact = downloadArtifactEither.left().value().getRight(); - } - return downloadedArtifact; - } - - private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper errorWrapper) { - Component component = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } else { - component = getComponentRes.left().value(); - } - return component; - } - - private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper errorWrapper) { - Component component = null; - Either, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null); - if (getComponentRes.isRight()) { - StorageOperationStatus status = getComponentRes.right().value(); - log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } else { - List value = getComponentRes.left().value(); - if (value.isEmpty()){ - log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid); - ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND; - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status)); - } else { - component = value.get(0); - } - } - return component; - } - - private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper errorWrapper, String parentId, ComponentTypeEnum componentType) { - String artifactId = null; - ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND; - StorageOperationStatus storageStatus; - ArtifactDefinition latestArtifact = null; - List artifacts = null; - Either, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId); - if (getArtifactsRes.isRight()) { - storageStatus = getArtifactsRes.right().value(); - log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus); - if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) { - actionStatus = componentsUtils.convertFromStorageResponse(storageStatus); - } - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - if (errorWrapper.isEmpty()) { - artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList()); - if (artifacts == null || artifacts.isEmpty()) { - log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - } - if (errorWrapper.isEmpty()) { - latestArtifact = artifacts.stream().max((a1, a2) -> { - int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion())); - if (compareRes == 0) { - compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate()); - } - return compareRes; - }).get(); - if (latestArtifact == null) { - log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID)); - } - } - if (errorWrapper.isEmpty()) { - artifactId = latestArtifact.getUniqueId(); - } - return artifactId; - } - - private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper errorWrapper) { - - Component component = null; - Either getUserRes = userBusinessLogic.getUser(userId, false); - if (getUserRes.isRight()) { - log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value()); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value())); - } - if (errorWrapper.isEmpty()) { - User modifier = getUserRes.left().value(); - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API); - Either checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus()); - errorWrapper.setInnerElement(checkoutRes.right().value()); - } else { - component = checkoutRes.left().value(); - } - } - return component; - } - - private void updateAuditParametersWithArtifactDefinition(Map additionalParams, ArtifactDefinition artifact) { - if (artifact == null) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); - if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ""); - } - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName()); - } - } - - private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { - Map json = new HashMap<>(); - String artifactName = artifact.getArtifactName(); - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel()); - json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType()); - json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription()); - json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData()); - json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName()); - return gson.toJson(json); - } + } + + private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) { + Map json = new HashMap<>(); + String artifactName = artifact.getArtifactName(); + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel()); + json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType()); + json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription()); + json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData()); + json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName()); + return gson.toJson(json); + } + + @VisibleForTesting + void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) { + this.nodeTemplateOperation = nodeTemplateOperation; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index 2e14028338..6756108387 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -39,7 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; /** * This class holds the business logic relevant for attributes manipulation. @@ -50,256 +49,256 @@ import fj.data.Either; @Component("attributeBusinessLogic") public class AttributeBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_ATTRIBUTE = "CreateAttribute"; - private static final String UPDATE_ATTRIBUTE = "UpdateAttribute"; - private static final String DELETE_ATTRIBUTE = "DeleteAttribute"; - - private static Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class.getName()); - - /** - * Created attribute on the resource with resourceId - * - * @param resourceId - * @param newAttributeDef - * @param userId - * @return AttributeDefinition if created successfully Or ResponseFormat - */ - public Either createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { - Either result = null; - Either resp = validateUserExists(userId, "create Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - try { - // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute does not exist in resource - if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); - } - Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } - // validate property default values - Either defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - - handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); - - // add the new attribute to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus from - // componentsUtils - Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - result = Either.left(either.left().value()); - - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { - boolean isExist = false; - if (attributes != null) { - isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); - } - return isExist; - - } - - /** - * @param resourceId - * @param attributeId - * @param userId - * @return - */ - public Either getAttribute(String resourceId, String attributeId, String userId) { - - Either resp = validateUserExists(userId, "get Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - List attributes = resource.getAttributes(); - if (attributes == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); - } else { - Either result; - // verify attribute exist in resource - Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); - - if (optionalAtt.isPresent()) { - result = Either.left(optionalAtt.get()); - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); - } - return result; - } - - } - - /** - * Updates Attribute on resource - * - * @param resourceId - * @param attributeId - * @param newAttDef - * @param userId - * @return - */ - public Either updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { - Either result = null; - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - try { - // Get the resource from DB - Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); - if (eitherResource.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = eitherResource.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute exist in resource - Either eitherAttribute = getAttribute(resourceId, attributeId, userId); - if (eitherAttribute.isRight()) { - return Either.right(eitherAttribute.right().value()); - } - Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - if (eitherAllDataTypes.isRight()) { - return Either.right(eitherAllDataTypes.right().value()); - } - - // validate attribute default values - Either defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value()); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - // add the new property to resource on graph - - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); - if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); - } - - - Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); - - if (eitherAttUpdate.isRight()) { - log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); - return result; - } - - result = Either.left(eitherAttUpdate.left().value()); - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - /** - * Deletes Attribute on resource - * - * @param resourceId - * @param attributeId - * @param userId - * @return - */ - public Either deleteAttribute(String resourceId, String attributeId, String userId) { - - Either result = null; - - Either resp = validateUserExists(userId, "delete Attribute", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - try { - // Get the resource from DB - Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); - if (eitherResource.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = eitherResource.left().value(); - - // verify that resource is checked-out and the user is the last updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // verify attribute exist in resource - Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); - if (eitherAttributeExist.isRight()) { - return Either.right(eitherAttributeExist.right().value()); - } - String attributeName = eitherAttributeExist.left().value().getName(); - - // delete attribute of resource from graph - StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); - if (eitherAttributeDelete != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); - return result; - } - - result = Either.left(eitherAttributeExist.left().value()); - return result; - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - } + private static final String CREATE_ATTRIBUTE = "CreateAttribute"; + private static final String UPDATE_ATTRIBUTE = "UpdateAttribute"; + private static final String DELETE_ATTRIBUTE = "DeleteAttribute"; + + private static final Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class); + + /** + * Created attribute on the resource with resourceId + * + * @param resourceId + * @param newAttributeDef + * @param userId + * @return AttributeDefinition if created successfully Or ResponseFormat + */ + public Either createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { + Either result = null; + Either resp = validateUserExists(userId, "create Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + try { + // Get the resource from DB + Either status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute does not exist in resource + if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); + } + Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + if (eitherAllDataTypes.isRight()) { + return Either.right(eitherAllDataTypes.right().value()); + } + // validate property default values + Either defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + + handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value()); + + // add the new attribute to resource on graph + // need to get StorageOpaerationStatus and convert to ActionStatus from + // componentsUtils + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + result = Either.left(either.left().value()); + + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { + boolean isExist = false; + if (attributes != null) { + isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); + } + return isExist; + + } + + /** + * @param resourceId + * @param attributeId + * @param userId + * @return + */ + public Either getAttribute(String resourceId, String attributeId, String userId) { + + Either resp = validateUserExists(userId, "get Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + // Get the resource from DB + Either status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + List attributes = resource.getAttributes(); + if (attributes == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); + } else { + Either result; + // verify attribute exist in resource + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); + + if (optionalAtt.isPresent()) { + result = Either.left(optionalAtt.get()); + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); + } + return result; + } + + } + + /** + * Updates Attribute on resource + * + * @param resourceId + * @param attributeId + * @param newAttDef + * @param userId + * @return + */ + public Either updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { + Either result = null; + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + try { + // Get the resource from DB + Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); + if (eitherResource.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = eitherResource.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute exist in resource + Either eitherAttribute = getAttribute(resourceId, attributeId, userId); + if (eitherAttribute.isRight()) { + return Either.right(eitherAttribute.right().value()); + } + Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + if (eitherAllDataTypes.isRight()) { + return Either.right(eitherAllDataTypes.right().value()); + } + + // validate attribute default values + Either defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value()); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + // add the new property to resource on graph + + StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value()); + if (validateAndUpdateAttribute != StorageOperationStatus.OK) { + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); + } + + + Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); + + if (eitherAttUpdate.isRight()) { + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); + return result; + } + + result = Either.left(eitherAttUpdate.left().value()); + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + /** + * Deletes Attribute on resource + * + * @param resourceId + * @param attributeId + * @param userId + * @return + */ + public Either deleteAttribute(String resourceId, String attributeId, String userId) { + + Either result = null; + + Either resp = validateUserExists(userId, "delete Attribute", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (lockResult != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + try { + // Get the resource from DB + Either eitherResource = toscaOperationFacade.getToscaElement(resourceId); + if (eitherResource.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = eitherResource.left().value(); + + // verify that resource is checked-out and the user is the last updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // verify attribute exist in resource + Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); + if (eitherAttributeExist.isRight()) { + return Either.right(eitherAttributeExist.right().value()); + } + String attributeName = eitherAttributeExist.left().value().getName(); + + // delete attribute of resource from graph + StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); + if (eitherAttributeDelete != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); + return result; + } + + result = Either.left(eitherAttributeExist.left().value()); + return result; + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index 14c451a3b0..e401cb14f5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - +import com.google.gson.JsonElement; +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -40,18 +37,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.IPropertyInputCommon; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; @@ -60,6 +49,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; @@ -78,696 +68,716 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.JsonElement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Function; -import fj.data.Either; +import static org.apache.commons.collections.CollectionUtils.isEmpty; public abstract class BaseBusinessLogic { - @Autowired - protected ComponentsUtils componentsUtils; - - @Autowired - protected IUserBusinessLogic userAdmin; - - @Autowired - protected IGraphLockOperation graphLockOperation; - - @Autowired - protected TitanDao titanDao; - - @Autowired - protected TitanGenericDao titanGenericDao; - - @Autowired - protected IElementOperation elementDao; - - @Autowired - protected IGroupOperation groupOperation; - - @Autowired - protected IGroupInstanceOperation groupInstanceOperation; - - @Autowired - protected IGroupTypeOperation groupTypeOperation; - - /*@Autowired - protected IArtifactOperation artifactOperation;*/ - @javax.annotation.Resource - protected ArtifactsOperations artifactToscaOperation; - -// @Autowired -// protected IAttributeOperation attributeOperation; - - @Autowired - protected PropertyOperation propertyOperation; - - @Autowired - protected ApplicationDataTypeCache applicationDataTypeCache; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } - - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } - - public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { - this.graphLockOperation = graphLockOperation; - } - - public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { - this.toscaOperationFacade = toscaOperationFacade; - } - - - private static Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class.getName()); - - public static final String EMPTY_VALUE = null; - - protected Either validateUserNotEmpty(User user, String ecompErrorContext) { - String userId = user.getUserId(); - - if (StringUtils.isEmpty(userId)) { - log.debug("User header is missing "); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - return Either.right(responseFormat); - } - return Either.left(user); - } - - protected Either validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { - return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); - } - - protected void validateUserExist(String userId, String ecompErrorContext, Wrapper errorWrapper) { - Either resp = validateUserExists(userId, ecompErrorContext, false); - if (resp.isRight()) { - errorWrapper.setInnerElement(resp.right().value()); - } - } - - public Either validateUserExistsActionStatus(String userId, String ecompErrorContext) { - Either eitherCreator = userAdmin.getUser(userId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("validateUserExists - not authorized user, userId {}", userId); - Either.right(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("validateUserExists - failed to authorize user, userId {}", userId); - } - log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); - return Either.right(eitherCreator.right().value()); - } - return Either.left(eitherCreator.left().value()); - } - - public Either validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { - Either eitherCreator = userAdmin.getUser(userId, inTransaction); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - ResponseFormat responseFormat; - if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - if (log.isDebugEnabled()) - log.debug("validateUserExists - not authorized user, userId {}", userId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - if (log.isDebugEnabled()) - log.debug("validateUserExists - failed to authorize user, userId {}", userId); - responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value()); - } - if (log.isDebugEnabled()) - log.debug("User is not listed. userId {}", userId); - BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); - return Either.right(responseFormat); - } - return Either.left(eitherCreator.left().value()); - } - - protected Either validateUserRole(User user, List roles) { - Role userRole = Role.valueOf(user.getRole()); - if (roles != null) { - if (!roles.contains(userRole)) { - if (log.isDebugEnabled()) - log.debug("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - return Either.left(Boolean.TRUE); - } - return Either.left(Boolean.FALSE); - } - - protected Either lockComponent(Component component, String ecompErrorContext) { - return lockComponent(component.getUniqueId(), component, ecompErrorContext); - } - - protected Either lockComponent(String componentId, Component component, String ecompErrorContext) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); - log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus); - return Either.right(responseFormat); - } - } - - protected void unlockComponent(Either either, Component component, boolean inTransaction) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - if (false == inTransaction) { - if (either == null || either.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - // unlock resource - graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); - } - - protected void unlockComponent(Either either, Component component) { - unlockComponent(either, component, false); - } - - protected Either validateJsonBody(T bodyObject, Class clazz) { - if (bodyObject == null) { - log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - return Either.left(true); - } - } - - protected Either validateComponentType(String componentType) { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum == null) { - log.debug("Invalid component type {}", componentType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); - } else { - return Either.left(componentTypeEnum); - } - } - - protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { - - if(filter == null){ - filter = new ComponentParametersView(); - } - Either componentFound = toscaOperationFacade.getToscaElement(componentId, filter); - if (componentFound.isRight()) { - StorageOperationStatus storageOperationStatus = componentFound.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", componentId); - return Either.right(responseFormat); - } - return Either.left(componentFound.left().value()); - } - - public Either validateCanWorkOnComponent(Component component, String userId) { - Either canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - log.debug("Component {} is not checked-out", component.getName()); - return canWork; - } - - // verify userId is not null - if (userId == null) { - log.debug("Current user userId is null"); - return canWork; - } - - // verify component last update user is the current user - String lastUpdaterUserId = component.getLastUpdaterUserId(); - if (!userId.equals(lastUpdaterUserId)) { - log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); - return canWork; - } - - // verify resource is not deleted - if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) { - log.debug("Component {} is marked as deleted", component.getUniqueId()); - return canWork; - } - - return Either.left(true); - } - - public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { - switch (parentComponentType) { - case SERVICE: - return ComponentTypeEnum.RESOURCE; - case RESOURCE: - return ComponentTypeEnum.RESOURCE; - case PRODUCT: - return ComponentTypeEnum.SERVICE; - default: - break; - } - return null; - } - - // For UT - public void setTitanGenericDao(TitanDao titanDao) { - this.titanDao = titanDao; - } - - protected Either, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { - Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus operationStatus = allDataTypes.right().value(); - if (operationStatus == TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); - } else { - BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - return Either.left(allDataTypes.left().value()); - } - - protected Either validatePropertyDefaultValue(IComplexDefaultValue property, Map dataTypes) { - String type = null; - String innerType = null; - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property {} type {}", property.getName(), property.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); - return Either.right(responseFormat); - } - type = property.getType(); - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight().booleanValue()) { - log.info("Invalid inner type for property {} type {}", property.getName(), property.getType() ); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); - return Either.right(responseFormat); - } - } - if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) { - log.info("Invalid default value for property {} type {}", property.getName(), property.getType() ); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); - } - return Either.right(responseFormat); - - } - return Either.left(true); - } - -// protected Either getResource(final String resourceId) { -// -// log.debug("Get resource with id {}", resourceId); -// Either status = resourceOperation.getResource(resourceId); -// if (status.isRight()) { -// log.debug("Resource with id {} was not found", resourceId); -// return Either.right(status.right().value()); -// } -// -// Resource resource = status.left().value(); -// if (resource == null) { -// BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId); -// log.debug("General Error while get resource with id {}", resourceId); -// return Either.right(StorageOperationStatus.GENERAL_ERROR); -// } -// return Either.left(resource); -// } - - protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map dataTypes) { - // convert property - ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType()); - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - - if (newAttributeDef != null) { - SchemaDefinition schema = newAttributeDef.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (schema.getProperty() != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newAttributeDef.getDefaultValue() != null) { - convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes); - newAttributeDef.setDefaultValue(convertedValue); - } - } - } - - protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper errorWrapper) { - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - - } - - protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper errorWrapper) { - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - } - - protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper errorWrapper) { - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - } - - } - - protected ToscaPropertyType getType(String propertyType) { - - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - return type; - - } - - protected void commitOrRollback(Either result) { - if (result == null || result.isRight()) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - - protected Either lockComponentByName(String name, Component component, String ecompErrorContext) { - ComponentTypeEnum componentType = component.getComponentType(); - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); - log.debug("Failed to lock component {} error - {}", name, actionStatus); - return Either.right(responseFormat); - } - } - - protected Either validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) { - - Either componentFound = null; - componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - - if (componentFound.isRight()) { - StorageOperationStatus storageOperationStatus = componentFound.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", componentId); - return Either.right(responseFormat); - } - return Either.left(componentFound.left().value()); - } - - protected Either validateFreeText(GroupProperty groupPropertyToUpdate) { - - Either ret; - final String groupTypeValue = groupPropertyToUpdate.getValue(); - if (!StringUtils.isEmpty(groupTypeValue)) { - if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, - NodeTypeEnum.Property.getName(), - String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH))); - } - - else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, - NodeTypeEnum.Property.getName())); - } else { - ret = Either.left(groupPropertyToUpdate); - } - - } else { - ret = Either.left(groupPropertyToUpdate); - } - return ret; - } - - @SuppressWarnings("unchecked") - protected > boolean enumHasValueFilter(String name, Function enumGetter, T... enumValues) { - T enumFound = enumGetter.apply(name); - return Arrays.asList(enumValues).contains(enumFound); - } - - protected Either validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map allDataTypes) { - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - innerType = propDef.getType(); - } - - Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); - log.trace("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - return Either.left(newValue); - } - - protected Either validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map allDataTypes) { - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - innerType = propDef.getType(); - } - - Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); - log.debug("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - return Either.left(newValue); - } - - public Either validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map dataTypes) { - log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); - ToscaPropertyType type = getType(propertyType); - - if (isValidate) { - - if (type == null) { - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); - if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", value, propertyType); - return Either.right(false); - } - JsonElement jsonElement = validateResult.left; - String valueFromJsonElement = getValueFromJsonElement(jsonElement); - return Either.left(valueFromJsonElement); - } - log.trace("before validating property type {}", propertyType); - boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.debug("The value {} of property from type {} is invalid", value, type); - return Either.right(false); - } - } - Object convertedValue = value; - if (false == isEmptyValue(value) && isValidate) { - PropertyValueConverter converter = type.getConverter(); - convertedValue = converter.convert(value, innerType, dataTypes); - } - return Either.left(convertedValue); - } - - public ImmutablePair validateAndUpdateRules(String propertyType, List rules, String innerType, Map dataTypes, boolean isValidate) { - - if (rules == null || rules.isEmpty() == true) { - return new ImmutablePair(null, true); - } - - for (PropertyRule rule : rules) { - String value = rule.getValue(); - Either updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); - if (updateResult.isRight()) { - Boolean status = updateResult.right().value(); - if (status == false) { - return new ImmutablePair(value, status); - } - } else { - String newValue = null; - Object object = updateResult.left().value(); - if (object != null) { - newValue = object.toString(); - } - rule.setValue(newValue); - } - } - - return new ImmutablePair(null, true); - } - - protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { - if (isEmptyValue(value)) { - return true; - } - - PropertyTypeValidator validator = type.getValidator(); - - boolean isValid = validator.isValid(value, innerType, dataTypes); - if (true == isValid) { - return true; - } else { - return false; - } - - } - - public boolean isEmptyValue(String value) { - if (value == null) { - return true; - } - return false; - } - - public boolean isNullParam(String value) { - if (value == null) { - return true; - } - return false; - } - - public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { - - List rules = resourceInstanceProperty.getRules(); - if (rules == null) { - PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId); - rules = new ArrayList<>(); - rules.add(propertyRule); - } else { - rules = sortRules(rules); - } - - propertyValueData.setRules(rules); - } - - private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { - List path = resourceInstanceProperty.getPath(); - // FOR BC. Since old Property values on VFC/VF does not have rules on - // graph. - // Update could be done on one level only, thus we can use this - // operation to avoid migration. - if (path == null || path.isEmpty() == true) { - path = new ArrayList<>(); - path.add(resourceInstanceId); - } - PropertyRule propertyRule = new PropertyRule(); - propertyRule.setRule(path); - propertyRule.setValue(propertyValueData.getValue()); - return propertyRule; - } - - private List sortRules(List rules) { - - // TODO: sort the rules by size and binary representation. - // (x, y, .+) --> 110 6 priority 1 - // (x, .+, z) --> 101 5 priority 2 - - return rules; - } - - protected String getValueFromJsonElement(JsonElement jsonElement) { - String value = null; - - if (jsonElement == null || jsonElement.isJsonNull()) { - value = EMPTY_VALUE; - } else { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - - return value; - } + private static final Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class); + + private static final String EMPTY_VALUE = null; + @Autowired + protected ComponentsUtils componentsUtils; + + @Autowired + protected IUserBusinessLogic userAdmin; + + @Autowired + protected IGraphLockOperation graphLockOperation; + + @Autowired + protected TitanDao titanDao; + + @Autowired + protected TitanGenericDao titanGenericDao; + + @Autowired + protected IElementOperation elementDao; + + @Autowired + protected IGroupOperation groupOperation; + + @Autowired + protected IGroupInstanceOperation groupInstanceOperation; + + @Autowired + protected IGroupTypeOperation groupTypeOperation; + + @Autowired + protected GroupBusinessLogic groupBusinessLogic; + + @Autowired + protected PolicyTypeOperation policyTypeOperation; + + @javax.annotation.Resource + protected ArtifactsOperations artifactToscaOperation; + + @Autowired + protected PropertyOperation propertyOperation; + + @Autowired + protected ApplicationDataTypeCache applicationDataTypeCache; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @Autowired + protected ApplicationDataTypeCache dataTypeCache; + + @Autowired + protected ForwardingPathOperation forwardingPathOperation; + + @javax.annotation.Resource + private UserValidations userValidations; + + protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } + + public void setUserValidations(UserValidations userValidations) { + this.userValidations = userValidations; + } + + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { + this.graphLockOperation = graphLockOperation; + } + + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation){ + this.forwardingPathOperation = forwardingPathOperation; + } + + public void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) { + this.policyTypeOperation = policyTypeOperation; + } + + + public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) { + this.dataTypeCache = dataTypeCache; + } + + public void setPropertyOperation(PropertyOperation propertyOperation) { + this.propertyOperation = propertyOperation; + } + + protected Either validateUserNotEmpty(User user, String ecompErrorContext) { + return userValidations.validateUserNotEmpty(user, ecompErrorContext); + } + + protected Either validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { + return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); + } + + protected void validateUserExist(String userId, String ecompErrorContext, Wrapper errorWrapper) { + userValidations.validateUserExist(userId, ecompErrorContext, errorWrapper); + } + + public Either validateUserExistsActionStatus(String userId, String ecompErrorContext) { + return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext); + } + + public Either validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { + return userValidations.validateUserExists(userId, ecompErrorContext, inTransaction); + } + + protected Either validateUserRole(User user, List roles) { + return userValidations.validateUserRole(user, roles); + } + + protected Either lockComponent(Component component, String ecompErrorContext) { + return lockComponent(component.getUniqueId(), component, ecompErrorContext); + } + + protected Either lockComponent(Component component, boolean shoulLock, String ecompErrorContext) { + return shoulLock ? lockComponent(component.getUniqueId(), component, ecompErrorContext) + .either(l -> Either.left(component), Either::right) : Either.left(component); + } + + protected Either lockComponent(String componentId, Component component, String ecompErrorContext) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); + log.debug("Failed to lock component {} error - {}", componentId, actionStatus); + return Either.right(responseFormat); + } + } + + protected void unlockComponent(Either either, Component component, boolean inTransaction) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + if (!inTransaction) { + if (either == null || either.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + // unlock resource + graphLockOperation.unlockComponent(component.getUniqueId(), nodeType); + } + + protected void unlockComponent(Either either, Component component) { + unlockComponent(either, component, false); + } + protected void unlockComponentById(Either either, String componentId) { + Either component = toscaOperationFacade.getToscaElement(componentId); + if(component.isLeft() && component != null) { + unlockComponent(either, component.left().value(), false); + } + } + + protected Either validateJsonBody(T bodyObject, Class clazz) { + if (bodyObject == null) { + log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + return Either.left(true); + } + } + + protected Either validateComponentType(String componentType) { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum == null) { + log.debug("Invalid component type {}", componentType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)); + } else { + return Either.left(componentTypeEnum); + } + } + + protected Either validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) { + if (filter == null) { + filter = new ComponentParametersView(); + } + return toscaOperationFacade.getToscaElement(componentId, filter) + .right() + .map(err -> handleGetComponentError(componentId, componentType, err)) + .left() + .bind(cmpt -> validateComponentType(cmpt, componentType)); + } + + private Either validateComponentType(Component cmpt, ComponentTypeEnum componentType) { + if (componentType != cmpt.getComponentType()) { + log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType); + ActionStatus cmptNotFoundError = componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType); + return Either.right(componentsUtils.getResponseFormat(cmptNotFoundError)); + } + return Either.left(cmpt); + } + + protected Either updatePropertyObjectValue(T property, boolean isInput) { + Either, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + if (allDataTypesEither.isRight()) { + TitanOperationStatus status = allDataTypesEither.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Map allDataTypes = allDataTypesEither.left().value(); + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + if (!isInput) { + ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } + return Either.left(newValue); + } + + public Either validateCanWorkOnComponent(Component component, String userId) { + Either canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + log.debug("Component {} is not checked-out", component.getName()); + return canWork; + } + + // verify userId is not null + if (userId == null) { + log.debug("Current user userId is null"); + return canWork; + } + + // verify component last update user is the current user + String lastUpdaterUserId = component.getLastUpdaterUserId(); + if (!userId.equals(lastUpdaterUserId)) { + log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId); + return canWork; + } + + // verify resource is not deleted + if (Boolean.TRUE.equals(component.getIsDeleted())) { + log.debug("Component {} is marked as deleted", component.getUniqueId()); + return canWork; + } + + return Either.left(true); + } + + public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) { + switch (parentComponentType) { + case SERVICE: + return ComponentTypeEnum.RESOURCE; + case RESOURCE: + return ComponentTypeEnum.RESOURCE; + case PRODUCT: + return ComponentTypeEnum.SERVICE; + default: + break; + } + return null; + } + + // For UT + public void setTitanGenericDao(TitanDao titanDao) { + this.titanDao = titanDao; + } + + protected Either, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) { + Either, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus operationStatus = allDataTypes.right().value(); + if (operationStatus == TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY)); + } else { + BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + return Either.left(allDataTypes.left().value()); + } + + protected Either validatePropertyDefaultValue(IComplexDefaultValue property, Map dataTypes) { + String type = null; + String innerType = null; + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + return Either.right(responseFormat); + } + type = property.getType(); + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight().booleanValue()) { + log.info("Invalid inner type for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + return Either.right(responseFormat); + } + } + if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) { + log.info("Invalid default value for property {} type {}", property.getName(), property.getType()); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); + } else { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); + } + return Either.right(responseFormat); + + } + return Either.left(true); + } + + + protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map dataTypes) { + // convert property + ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType()); + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + + if (newAttributeDef != null) { + SchemaDefinition schema = newAttributeDef.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (schema.getProperty() != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newAttributeDef.getDefaultValue() != null) { + convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes); + newAttributeDef.setDefaultValue(convertedValue); + } + } + } + + protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper errorWrapper) { + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + + } + + protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper errorWrapper) { + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + } + + protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper errorWrapper) { + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + } + + protected ToscaPropertyType getType(String propertyType) { + return ToscaPropertyType.isValidType(propertyType); + } + + protected void commitOrRollback(Either result) { + if (result == null || result.isRight()) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + + protected Either lockComponentByName(String name, Component component, String ecompErrorContext) { + ComponentTypeEnum componentType = component.getComponentType(); + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName()); + log.debug("Failed to lock component {} error - {}", name, actionStatus); + return Either.right(responseFormat); + } + } + + protected Either validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) { + return toscaOperationFacade.getToscaElement(componentId, componentParametersView) + .right() + .map(err -> handleGetComponentError(componentId, componentType, err)); + + } + + private ResponseFormat handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError); + return responseFormat; + } + + protected Either validateFreeText(GroupProperty groupPropertyToUpdate) { + + Either ret; + final String groupTypeValue = groupPropertyToUpdate.getValue(); + if (!StringUtils.isEmpty(groupTypeValue)) { + if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, + NodeTypeEnum.Property.getName(), + String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH))); + } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, + NodeTypeEnum.Property.getName())); + } else { + ret = Either.left(groupPropertyToUpdate); + } + + } else { + ret = Either.left(groupPropertyToUpdate); + } + return ret; + } + + + @SafeVarargs + static > boolean enumHasValueFilter(String name, Function enumGetter, T... enumValues) { + T enumFound = enumGetter.apply(name); + return Arrays.asList(enumValues).contains(enumFound); + } + + Either validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.trace("After validateAndUpdateRules. pair = {}", pair); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + protected Either validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map allDataTypes) { + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + innerType = propDef.getType(); + } + + Either isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + ImmutablePair pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (Boolean.FALSE.equals(pair.getRight())) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + return Either.left(newValue); + } + + public Either validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map dataTypes) { + log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value); + ToscaPropertyType type = getType(propertyType); + + if (isValidate) { + + if (type == null) { + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + if (Boolean.FALSE.equals(validateResult.right)) { + log.debug("The value {} of property from type {} is invalid", value, propertyType); + return Either.right(false); + } + JsonElement jsonElement = validateResult.left; + String valueFromJsonElement = getValueFromJsonElement(jsonElement); + return Either.left(valueFromJsonElement); + } + log.trace("before validating property type {}", propertyType); + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (!isValidProperty) { + log.debug("The value {} of property from type {} is invalid", value, type); + return Either.right(false); + } + } + Object convertedValue = value; + if (!isEmptyValue(value) && isValidate) { + PropertyValueConverter converter = type.getConverter(); + convertedValue = converter.convert(value, innerType, dataTypes); + } + return Either.left(convertedValue); + } + + public ImmutablePair validateAndUpdateRules(String propertyType, List rules, String innerType, Map dataTypes, boolean isValidate) { + + if (rules == null || rules.isEmpty()) { + return ImmutablePair.of(null, true); + } + + for (PropertyRule rule : rules) { + String value = rule.getValue(); + Either updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); + if (updateResult.isRight()) { + Boolean status = updateResult.right().value(); + if (Boolean.FALSE.equals(status)) { + return ImmutablePair.of(value, status); + } + } else { + String newValue = null; + Object object = updateResult.left().value(); + if (object != null) { + newValue = object.toString(); + } + rule.setValue(newValue); + } + } + + return ImmutablePair.of(null, true); + } + + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + return validator.isValid(value, innerType, dataTypes); + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } + + public boolean isNullParam(String value) { + if (value == null) { + return true; + } + return false; + } + + public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + + List rules = resourceInstanceProperty.getRules(); + if (rules == null) { + PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId); + rules = new ArrayList<>(); + rules.add(propertyRule); + } else { + rules = sortRules(rules); + } + + propertyValueData.setRules(rules); + } + + private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { + List path = resourceInstanceProperty.getPath(); + // FOR BC. Since old Property values on VFC/VF does not have rules on + // graph. + // Update could be done on one level only, thus we can use this + // operation to avoid migration. + if (isEmpty(path)) { + path = new ArrayList<>(); + path.add(resourceInstanceId); + } + PropertyRule propertyRule = new PropertyRule(); + propertyRule.setRule(path); + propertyRule.setValue(propertyValueData.getValue()); + return propertyRule; + } + + private List sortRules(List rules) { + + // TODO: sort the rules by size and binary representation. + // (x, y, .+) --> 110 6 priority 1 + // (x, .+, z) --> 101 5 priority 2 + + return rules; + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java index 5cf42cedd6..caf051ec81 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import javax.annotation.Resource; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -41,83 +34,87 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; @Component("capabilityTypeImportManager") public class CapabilityTypeImportManager { - private static Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class.getName()); - @Resource - private CapabilityTypeOperation capabilityTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - public Either, ResponseFormat> createCapabilityTypes(String capabilityYml) { - Either, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml); - if (capabilityTypes.isRight()) { - ActionStatus status = capabilityTypes.right().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null); - return Either.right(responseFormat); - } - return createCapabilityTypesByDao(capabilityTypes.left().value()); - - } - - private Either, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) { - return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData)); - - } - - private Either, ResponseFormat> createCapabilityTypesByDao(List capabilityTypesToCreate) { - List createdCapabilities = new ArrayList<>(); - Either, ResponseFormat> eitherResult = Either.left(createdCapabilities); - Iterator capTypeItr = capabilityTypesToCreate.iterator(); - boolean stopDao = false; - while (capTypeItr.hasNext() && !stopDao) { - CapabilityTypeDefinition capabilityType = capTypeItr.next(); - - log.info("send capabilityType {} to dao for create", capabilityType.getType()); - Either dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType); - if (dataModelResponse.isRight()) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingCapabilityTypeError, "Create CapabilityTypes"); - BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type"); - log.debug("failed to create capabilityType: {}", capabilityType.getType()); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType); - eitherResult = Either.right(responseFormat); - stopDao = true; - } - - } else { - createdCapabilities.add(capabilityType); - } - if (!capTypeItr.hasNext()) { - log.info("capabilityTypes were created successfully!!!"); - } - - } - - return eitherResult; - - } - - private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map toscaJson) { - CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); - - capabilityType.setType(capabilityTypeName); - - // Description - final Consumer descriptionSetter = description -> capabilityType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values)); - - return capabilityType; - } + private static final Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class); + @Resource + private CapabilityTypeOperation capabilityTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + public Either, ResponseFormat> createCapabilityTypes(String capabilityYml) { + Either, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml); + if (capabilityTypes.isRight()) { + ActionStatus status = capabilityTypes.right().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null); + return Either.right(responseFormat); + } + return createCapabilityTypesByDao(capabilityTypes.left().value()); + + } + + private Either, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) { + return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData)); + + } + + private Either, ResponseFormat> createCapabilityTypesByDao(List capabilityTypesToCreate) { + List createdCapabilities = new ArrayList<>(); + Either, ResponseFormat> eitherResult = Either.left(createdCapabilities); + Iterator capTypeItr = capabilityTypesToCreate.iterator(); + boolean stopDao = false; + while (capTypeItr.hasNext() && !stopDao) { + CapabilityTypeDefinition capabilityType = capTypeItr.next(); + + log.info("send capabilityType {} to dao for create", capabilityType.getType()); + Either dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType); + if (dataModelResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type"); + log.debug("failed to create capabilityType: {}", capabilityType.getType()); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType); + eitherResult = Either.right(responseFormat); + stopDao = true; + } + + } else { + createdCapabilities.add(capabilityType); + } + if (!capTypeItr.hasNext()) { + log.info("capabilityTypes were created successfully!!!"); + } + + } + + return eitherResult; + + } + + private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map toscaJson) { + CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); + + capabilityType.setType(capabilityTypeName); + + // Description + final Consumer descriptionSetter = description -> capabilityType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values)); + + return capabilityType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java index 1f5770856b..31db9651c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java @@ -1,5 +1,18 @@ package org.openecomp.sdc.be.components.impl; +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.KeyspaceMetadata; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.Session; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils; +import org.openecomp.sdc.be.dao.cassandra.schema.Table; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; @@ -10,178 +23,163 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import javax.annotation.PostConstruct; +@Component("cassandra-health-check") +public class CassandraHealthCheck { -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils; -import org.openecomp.sdc.be.dao.cassandra.schema.Table; -import org.openecomp.sdc.common.util.GeneralUtility; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.Metadata; -import com.datastax.driver.core.Session; + private static final Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class); -@Component("cassandra-health-check") -public class CassandraHealthCheck { - - - private static Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class.getName()); - - private String localDataCenterName = null; - - private Set sdcKeyspaces = new HashSet(); - - private int HC_FormulaNumber; - - @PostConstruct - private void init() { - - //Initialize local data center name - this field must be filled by DevOps - localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter(); - - if (GeneralUtility.isEmptyString(localDataCenterName)) { - log.error("localDataCenter Name in configuration.yaml is missing."); - return; - } - - //Collect all SDC keyspaces - for (Table table : Table.values()) { - sdcKeyspaces.add(table.getTableDescription().getKeyspace()); - } - - String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); - Properties prop = new Properties(); - InputStream titanProp = null; - try { - //load a properties file - titanProp = new FileInputStream(titanCfgFile); - prop.load(titanProp); - //Add titan keyspace - String titanKeyspace = prop.getProperty("storage.cassandra.keyspace"); - if (!GeneralUtility.isEmptyString(titanKeyspace)) { - sdcKeyspaces.add(titanKeyspace); - } - } catch (Exception e) { - log.error("Failed to open titen.properties file , url is : {}", titanCfgFile); - } - - log.info("All sdc keyspaces are : {}", sdcKeyspaces); - - //Calculate the Formula of Health Check - Cluster cluster = null; - try { - - log.info("creating cluster for Cassandra Health Check."); - //Create cluster from nodes in cassandra configuration - cluster = SdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); - return; - } - - Metadata metadata = cluster.getMetadata(); - - if (metadata == null) { - log.error("Failure get cassandra metadata."); - return; - } - - log.info("Cluster Metadata: {}", metadata.toString()); - List keyspaces = metadata.getKeyspaces(); - List replactionFactorList = new ArrayList(); - - //Collect the keyspaces Replication Factor of current localDataCenter - for (KeyspaceMetadata keyspace : keyspaces) { - - if (sdcKeyspaces.contains(keyspace.getName())) { - - log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication()); - Map replicationOptions = keyspace.getReplication(); - - //In 1 site with one data center - if (replicationOptions.containsKey("replication_factor")) { - replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor"))); - } - //In multiple sites with some data center - else if (replicationOptions.containsKey(localDataCenterName)) { - replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName))); - } - } - } - - if (replactionFactorList.size() == 0) { - log.error("Replication factor NOT found in all keyspaces"); - return; - } - - int maxReplicationFactor = Collections.max(replactionFactorList); - log.info("maxReplication Factor is: {}", maxReplicationFactor); - - int localQuorum = maxReplicationFactor/2 + 1; - log.info("localQuorum is: {}", localQuorum); - - HC_FormulaNumber = maxReplicationFactor - localQuorum; - - log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber); - - - } catch (Exception e) { - log.error("create cassandra cluster failed with exception.", e); - } finally { - if (cluster != null) { - cluster.close(); - } - } - - } - - public boolean getCassandraStatus() { - - if (GeneralUtility.isEmptyString(localDataCenterName)) { - log.error("localDataCenter Name in configuration.yaml is missing."); - return false; - } - - Cluster cluster = null; - Session session = null; - try { - log.info("creating cluster for Cassandra for monitoring."); - cluster = SdcSchemaUtils.createCluster(); - if (cluster == null) { - log.error("Failure create cassandra cluster."); - return false; - } - session = cluster.connect(); - Metadata metadata = cluster.getMetadata(); - - if (metadata == null) { - log.error("Failure get cassandra metadata."); - return false; - } - - log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size()); - - //Count the number of data center nodes that are down - Long downHostsNumber = metadata.getAllHosts().stream() - .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count(); - - log.info("The cassandra down nodes number is {}", downHostsNumber.toString()); - return (HC_FormulaNumber >= downHostsNumber); - - } catch (Exception e) { - log.error("create cassandra cluster failed with exception.", e); - return false; - } finally { - if (session != null) { + private String localDataCenterName = null; + + private Set sdcKeyspaces = new HashSet(); + + private int HC_FormulaNumber; + + @PostConstruct + private void init() { + + //Initialize local data center name - this field must be filled by DevOps + localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter(); + + if (GeneralUtility.isEmptyString(localDataCenterName)) { + log.error("localDataCenter Name in configuration.yaml is missing."); + return; + } + + //Collect all SDC keyspaces + for (Table table : Table.values()) { + sdcKeyspaces.add(table.getTableDescription().getKeyspace()); + } + + String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile(); + Properties prop = new Properties(); + InputStream titanProp = null; + try { + //load a properties file + titanProp = new FileInputStream(titanCfgFile); + prop.load(titanProp); + //Add titan keyspace + String titanKeyspace = prop.getProperty("storage.cassandra.keyspace"); + if (!GeneralUtility.isEmptyString(titanKeyspace)) { + sdcKeyspaces.add(titanKeyspace); + } + } catch (Exception e) { + log.error("Failed to open titen.properties file , url is : {}", titanCfgFile, e); + } + + log.info("All sdc keyspaces are : {}", sdcKeyspaces); + + //Calculate the Formula of Health Check + Cluster cluster = null; + try { + + log.info("creating cluster for Cassandra Health Check."); + //Create cluster from nodes in cassandra configuration + cluster = SdcSchemaUtils.createCluster(); + if (cluster == null) { + log.error("Failure create cassandra cluster."); + return; + } + + Metadata metadata = cluster.getMetadata(); + + if (metadata == null) { + log.error("Failure get cassandra metadata."); + return; + } + + log.info("Cluster Metadata: {}", metadata); + List keyspaces = metadata.getKeyspaces(); + List replactionFactorList = new ArrayList(); + + //Collect the keyspaces Replication Factor of current localDataCenter + for (KeyspaceMetadata keyspace : keyspaces) { + + if (sdcKeyspaces.contains(keyspace.getName())) { + + log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication()); + Map replicationOptions = keyspace.getReplication(); + + //In 1 site with one data center + if (replicationOptions.containsKey("replication_factor")) { + replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor"))); + } + //In multiple sites with some data center + else if (replicationOptions.containsKey(localDataCenterName)) { + replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName))); + } + } + } + + if (replactionFactorList.size() == 0) { + log.error("Replication factor NOT found in all keyspaces"); + return; + } + + int maxReplicationFactor = Collections.max(replactionFactorList); + log.info("maxReplication Factor is: {}", maxReplicationFactor); + + int localQuorum = maxReplicationFactor/2 + 1; + log.info("localQuorum is: {}", localQuorum); + + HC_FormulaNumber = maxReplicationFactor - localQuorum; + + log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber); + + + } catch (Exception e) { + log.error("create cassandra cluster failed with exception.", e); + } finally { + if (cluster != null) { + cluster.close(); + } + } + + } + + public boolean getCassandraStatus() { + + if (GeneralUtility.isEmptyString(localDataCenterName)) { + log.error("localDataCenter Name in configuration.yaml is missing."); + return false; + } + + Cluster cluster = null; + Session session = null; + try { + log.info("creating cluster for Cassandra for monitoring."); + cluster = SdcSchemaUtils.createCluster(); + if (cluster == null) { + log.error("Failure create cassandra cluster."); + return false; + } + session = cluster.connect(); + Metadata metadata = cluster.getMetadata(); + + if (metadata == null) { + log.error("Failure get cassandra metadata."); + return false; + } + + log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size()); + + //Count the number of data center nodes that are down + Long downHostsNumber = metadata.getAllHosts().stream() + .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count(); + + log.info("The cassandra down nodes number is {}", downHostsNumber); + return HC_FormulaNumber >= downHostsNumber; + + } catch (Exception e) { + log.error("create cassandra cluster failed with exception.", e); + return false; + } finally { + if (session != null) { session.close(); } - if (cluster != null) { - cluster.close(); - } - } - } + if (cluster != null) { + cluster.close(); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java index 57ab46346a..fa662898d8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils; @@ -45,230 +39,229 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; @Component("categoriesImportManager") public class CategoriesImportManager { - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private IElementOperation elementOperation; - private static Logger log = LoggerFactory.getLogger(CategoriesImportManager.class.getName()); + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - public Either>, ResponseFormat> createCategories(String categoriesTypesYml) { + private static final Logger log = LoggerFactory.getLogger(CategoriesImportManager.class); - Map> allCategories = createCategoriesFromYml(categoriesTypesYml); - return createCategoriesByDao(allCategories); - } + public Either>, ResponseFormat> createCategories(String categoriesTypesYml) { - private Either>, ResponseFormat> createCategoriesByDao(Map> allCategories) { - Map> result = new HashMap<>(); - log.debug("createCategoriesByDao: starting to create Categories."); - for (Map.Entry> entry : allCategories.entrySet()) { - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey()); - NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY); - NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY); - NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING); - log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); - List newCategoriesvalue = new ArrayList<>(); - for (CategoryDefinition category : entry.getValue()) { + Map> allCategories = createCategoriesFromYml(categoriesTypesYml); + return createCategoriesByDao(allCategories); + } - Either createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory); - if (createdCategoryRes.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } + private Either>, ResponseFormat> createCategoriesByDao(Map> allCategories) { + Map> result = new HashMap<>(); + log.debug("createCategoriesByDao: starting to create Categories."); + for (Map.Entry> entry : allCategories.entrySet()) { + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey()); + NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY); + NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY); + NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING); + log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup); + List newCategoriesvalue = new ArrayList<>(); + for (CategoryDefinition category : entry.getValue()) { - CategoryDefinition newcategory = createdCategoryRes.left().value(); - String categoryId = newcategory.getUniqueId(); - log.debug("createCategoriesByDao: create category was successful {}", newcategory); - List newsubcategories = new ArrayList<>(); - List subcategories = category.getSubcategories(); - if (subcategories != null) { - for (SubCategoryDefinition subcategory : subcategories) { - Either createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); - if (createdSubCategory.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); - List groupings = subcategory.getGroupings(); - if (groupings != null) { - List newgroupings = new ArrayList<>(); - for (GroupingDefinition grouping : groupings) { - Either createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); - if (createdGrouping.isRight()) { - return Either.right(createdCategoryRes.right().value()); - } - newgroupings.add(createdGrouping.left().value()); - } - newsubcategory.setGroupings(newgroupings); - } - newsubcategories.add(newsubcategory); - } - newcategory.setSubcategories(newsubcategories); - } - newCategoriesvalue.add(newcategory); - } - result.put(entry.getKey(), newCategoriesvalue); - } - return Either.left(result); - } + Either createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory); + if (createdCategoryRes.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } - private Either createGroupingDeo(Map.Entry> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { + CategoryDefinition newcategory = createdCategoryRes.left().value(); + log.debug("createCategoriesByDao: create category was successful {}", newcategory); + List newsubcategories = new ArrayList<>(); + List subcategories = category.getSubcategories(); + if (subcategories != null) { + for (SubCategoryDefinition subcategory : subcategories) { + Either createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory); + if (createdSubCategory.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } + SubCategoryDefinition newsubcategory = createdSubCategory.left().value(); + List groupings = subcategory.getGroupings(); + if (groupings != null) { + List newgroupings = new ArrayList<>(); + for (GroupingDefinition grouping : groupings) { + Either createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup); + if (createdGrouping.isRight()) { + return Either.right(createdCategoryRes.right().value()); + } + newgroupings.add(createdGrouping.left().value()); + } + newsubcategory.setGroupings(newgroupings); + } + newsubcategories.add(newsubcategory); + } + newcategory.setSubcategories(newsubcategories); + } + newCategoriesvalue.add(newcategory); + } + result.put(entry.getKey(), newCategoriesvalue); + } + return Either.left(result); + } - log.debug("createGroupingDeo: creating grouping {}", grouping); - Either createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); - if (createdGrouping.isRight()) { - if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { - log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); - String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); - createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); - if (createdGrouping.isRight()) { - log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup); - return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); - } - } - log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), - category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null, - createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null); - - return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); - } else { - log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value()); - } - return Either.left(createdGrouping.left().value()); + private Either createGroupingDeo(Map.Entry> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) { - } + log.debug("createGroupingDeo: creating grouping {}", grouping); + Either createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup); + if (createdGrouping.isRight()) { + if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) { + log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName()); + String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName()); + createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId); + if (createdGrouping.isRight()) { + log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup); + return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); + } + } + log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(), + category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null, + createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null); - private Either createSubCategorieDeo(Map.Entry> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) { - log.debug("createSubCategorieDeo: creating subcategory {}", subcategory); - Either createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); - if (createdSubCategory.isRight()) { - if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { - log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); - String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); - createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); - if (createdSubCategory.isRight()) { - log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory); - return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); - } - } else { - log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); - return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); - } - } else { - log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value()); - } - return Either.left(createdSubCategory.left().value()); - } + return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value())); + } else { + log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value()); + } + return Either.left(createdGrouping.left().value()); - private Either createCategorieDeo(Map.Entry> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) { - log.debug("createCategorieDeo: creating category {}", category); - Either createdCategory = elementOperation.createCategory(category, nodeTypeCategory); - if (createdCategory.isRight()) { - log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); - if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { - return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); - } else { - log.debug("createCategorieDeo: category exists {} retriving.", category); - String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory); - createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId); - if (createdCategory.isRight()) { - log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory); - return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); - } - } - } else { - log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value()); - } - return Either.left(createdCategory.left().value()); - } + } - private Map> createCategoriesFromYml(String categoriesTypesYml) { - Map toscaJson = (Map) new Yaml().load(categoriesTypesYml); - Map> allCategories = new HashMap<>(); + private Either createSubCategorieDeo(Map.Entry> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) { + log.debug("createSubCategorieDeo: creating subcategory {}", subcategory); + Either createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory); + if (createdSubCategory.isRight()) { + if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) { + log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName()); + String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName()); + createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId); + if (createdSubCategory.isRight()) { + log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory); + return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); + } + } else { + log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value()); + return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value())); + } + } else { + log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value()); + } + return Either.left(createdSubCategory.left().value()); + } - Iterator> categoryEntryItr = toscaJson.entrySet().iterator(); - while (categoryEntryItr.hasNext()) { - Entry categoryTypeEntry = categoryEntryItr.next(); - String categoryType = categoryTypeEntry.getKey(); - List categoriesPerType = null; - Map categoryPerType = null; - switch (categoryType) { - case ComponentTypeEnum.SERVICE_PARAM_NAME: - categoryPerType = (Map) categoryTypeEntry.getValue(); - categoriesPerType = createServiceCategories(categoryPerType); - break; - case ComponentTypeEnum.RESOURCE_PARAM_NAME: - categoryPerType = (Map) categoryTypeEntry.getValue(); - categoriesPerType = createResourceCategories(categoryPerType); - break; - case ComponentTypeEnum.PRODUCT_PARAM_NAME: - // TODO - break; - default: - log.debug("Not supported category type - {}", categoryType); - break; - } - if (categoriesPerType != null) { - allCategories.put(categoryType, categoriesPerType); - } - } - return allCategories; - } + private Either createCategorieDeo(Map.Entry> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) { + log.debug("createCategorieDeo: creating category {}", category); + Either createdCategory = elementOperation.createCategory(category, nodeTypeCategory); + if (createdCategory.isRight()) { + log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value()); + if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) { + return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); + } else { + log.debug("createCategorieDeo: category exists {} retriving.", category); + String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory); + createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId); + if (createdCategory.isRight()) { + log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory); + return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value())); + } + } + } else { + log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value()); + } + return Either.left(createdCategory.left().value()); + } - private List createServiceCategories(Map categories) { - List categroiesDef = new ArrayList<>(); - String catName = null; - List icons = null; - for (Entry entry : categories.entrySet()) { - CategoryDefinition catDef = new CategoryDefinition(); - Map category = (Map) entry.getValue(); - catName = (String) category.get("name"); - catDef.setName(catName); - icons = (List) category.get("icons"); - catDef.setIcons(icons); - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); - catDef.setNormalizedName(normalizedName); - categroiesDef.add(catDef); - } + private Map> createCategoriesFromYml(String categoriesTypesYml) { + Map toscaJson = (Map) new Yaml().load(categoriesTypesYml); + Map> allCategories = new HashMap<>(); - return categroiesDef; - } + Iterator> categoryEntryItr = toscaJson.entrySet().iterator(); + while (categoryEntryItr.hasNext()) { + Entry categoryTypeEntry = categoryEntryItr.next(); + String categoryType = categoryTypeEntry.getKey(); + List categoriesPerType = null; + Map categoryPerType = null; + switch (categoryType) { + case ComponentTypeEnum.SERVICE_PARAM_NAME: + categoryPerType = (Map) categoryTypeEntry.getValue(); + categoriesPerType = createServiceCategories(categoryPerType); + break; + case ComponentTypeEnum.RESOURCE_PARAM_NAME: + categoryPerType = (Map) categoryTypeEntry.getValue(); + categoriesPerType = createResourceCategories(categoryPerType); + break; + case ComponentTypeEnum.PRODUCT_PARAM_NAME: + // TODO + break; + default: + log.debug("Not supported category type - {}", categoryType); + break; + } + if (categoriesPerType != null) { + allCategories.put(categoryType, categoriesPerType); + } + } + return allCategories; + } - private List createResourceCategories(Map categoryPerType) { - List categroiesDef = new ArrayList<>(); - for (Map.Entry entry : categoryPerType.entrySet()) { - Map category = (Map) entry.getValue(); - CategoryDefinition catDef = new CategoryDefinition(); - String catName = (String) category.get("name"); - catDef.setName(catName); - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); - catDef.setNormalizedName(normalizedName); - Map subcategories = (Map) category.get("subcategories"); - List subcateDef = new ArrayList<>(); - for (Entry subcategory : subcategories.entrySet()) { - Map subcategoryInfo = (Map) subcategory.getValue(); - SubCategoryDefinition subDef = new SubCategoryDefinition(); - String subcategoryName = (String) subcategoryInfo.get("name"); - subDef.setName(subcategoryName); - List subcategoryIcons = (List) subcategoryInfo.get("icons"); - subDef.setIcons(subcategoryIcons); - normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName); - subDef.setNormalizedName(normalizedName); - subcateDef.add(subDef); - } + private List createServiceCategories(Map categories) { + List categroiesDef = new ArrayList<>(); + String catName = null; + List icons = null; + for (Entry entry : categories.entrySet()) { + CategoryDefinition catDef = new CategoryDefinition(); + Map category = (Map) entry.getValue(); + catName = (String) category.get("name"); + catDef.setName(catName); + icons = (List) category.get("icons"); + catDef.setIcons(icons); + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); + catDef.setNormalizedName(normalizedName); + categroiesDef.add(catDef); + } - catDef.setSubcategories(subcateDef); - categroiesDef.add(catDef); - } - return categroiesDef; - } + return categroiesDef; + } - public static void setLog(Logger log) { - CategoriesImportManager.log = log; - } + private List createResourceCategories(Map categoryPerType) { + List categroiesDef = new ArrayList<>(); + for (Map.Entry entry : categoryPerType.entrySet()) { + Map category = (Map) entry.getValue(); + CategoryDefinition catDef = new CategoryDefinition(); + String catName = (String) category.get("name"); + catDef.setName(catName); + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName); + catDef.setNormalizedName(normalizedName); + Map subcategories = (Map) category.get("subcategories"); + List subcateDef = new ArrayList<>(); + for (Entry subcategory : subcategories.entrySet()) { + Map subcategoryInfo = (Map) subcategory.getValue(); + SubCategoryDefinition subDef = new SubCategoryDefinition(); + String subcategoryName = (String) subcategoryInfo.get("name"); + subDef.setName(subcategoryName); + List subcategoryIcons = (List) subcategoryInfo.get("icons"); + subDef.setIcons(subcategoryIcons); + normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName); + subDef.setNormalizedName(normalizedName); + subcateDef.add(subDef); + } + catDef.setSubcategories(subcateDef); + categroiesDef.add(catDef); + } + return categroiesDef; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java index 31c665686e..055e479d0d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java @@ -20,27 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.CapabilityTypeDefinition; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.PolicyTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.exception.ResponseFormat; @@ -49,260 +35,279 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; -import jersey.repackaged.com.google.common.base.Function; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; @Component("commonImportManager") public class CommonImportManager { - private static Logger log = LoggerFactory.getLogger(CommonImportManager.class.getName()); - - @Resource - private ComponentsUtils componentsUtils; - @Resource - private PropertyOperation propertyOperation; - - protected void setProperties(Map toscaJson, Consumer> consumer) { - consumer.accept(getProperties(toscaJson)); - } - - private List getProperties(Map toscaJson) { - List values = null; - Either, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson); - - if (properties.isLeft()) { - values = new ArrayList<>(); - Map propertiesMap = properties.left().value(); - if (propertiesMap != null && propertiesMap.isEmpty() == false) { - - for (Entry entry : propertiesMap.entrySet()) { - String propName = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition); - newPropertyDefinition.setName(propName); - values.add(newPropertyDefinition); - } - } - } - - return values; - } - - protected void setPropertiesMap(Map toscaJson, Consumer> consumer) { - final List properties = getProperties(toscaJson); - if (properties != null) { - Map collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); - consumer.accept(collect); - } - - } - - interface ICreateElementType { - ElementType createElement(T1 firstArg, T2 secondArg); - } - - protected Either, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType, ElementDefinition> createApi) { - - List elementTypes = new ArrayList<>(); - try { - Map toscaJson = (Map) new Yaml().load(elementTypesYml); - - Iterator> elementTypesEntryItr = toscaJson.entrySet().iterator(); - while (elementTypesEntryItr.hasNext()) { - Entry elementTypeNameDataEntry = elementTypesEntryItr.next(); - String elementTypeName = elementTypeNameDataEntry.getKey(); - Map elementTypeJsonData = (Map) elementTypeNameDataEntry.getValue(); - ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData); - elementTypes.add(elementDefinition); - - } - - } catch (Exception e) { - log.debug("Failed to yaml file {}", elementTypesYml, e); - return Either.right(ActionStatus.INVALID_YAML_FILE); - } - return Either.left(elementTypes); - } - - protected void setField(Map toscaJson, String fieldName, Consumer setter) { - if (toscaJson.containsKey(fieldName)) { - FieldType fieldValue = (FieldType) toscaJson.get(fieldName); - setter.accept(fieldValue); - } - - } - - public enum ElementTypeEnum { - PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType - }; - - private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) { - ActionStatus ret; - switch (elementTypeEnum) { - case GroupType: - ret = componentsUtils.convertFromStorageResponseForGroupType(status); - break; - case DataType: - ret = componentsUtils.convertFromStorageResponseForDataType(status); - break; - case CapabilityType: - ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); - break; - case InterfaceLifecycleType: - ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); - break; - default: - ret = componentsUtils.convertFromStorageResponse(status); - break; - } - return ret; - } - - private ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) { - ResponseFormat ret; - switch (elementTypeEnum) { - case GroupType: - ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); - break; - case PolicyType: - ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); - break; - case DataType: - ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); - break; - case CapabilityType: - ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); - break; - - default: - ret = componentsUtils.getResponseFormat(actionStatus); - break; - } - return ret; - } - - protected Either>, ResponseFormat> createElementTypesByDao(List elementTypesToCreate, - Function> validator, Function> elementInfoGetter, - Function> elementFetcher, Function> elementAdder, - BiFunction> elementUpgrader) { - - List> createdElementTypes = new ArrayList<>(); - - Either>, ResponseFormat> eitherResult = Either.left(createdElementTypes); - - Iterator elementTypeItr = elementTypesToCreate.iterator(); - - try { - - while (elementTypeItr.hasNext()) { - ElementTypeDefinition elementType = elementTypeItr.next(); - final ImmutablePair elementInfo = elementInfoGetter.apply(elementType); - ElementTypeEnum elementTypeEnum = elementInfo.left; - String elementName = elementInfo.right; - - Either validateElementType = validator.apply(elementType); - if (validateElementType.isRight()) { - ResponseFormat responseFormat = validateElementType.right().value(); - log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage()); - eitherResult = Either.right(responseFormat); - break; - } - - log.info("send {} : {} to dao for create", elementTypeEnum.name(), elementName); - - Either findElementType = elementFetcher.apply(elementName); - if (findElementType.isRight()) { - StorageOperationStatus status = findElementType.right().value(); - log.debug("searched {} finished with result:{}", elementTypeEnum.name(), status.name()); - if (status != StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType); - eitherResult = Either.right(responseFormat); - break; - } else { - Either dataModelResponse = elementAdder.apply(elementType); - - if (dataModelResponse.isRight()) { - try { - BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name()); - log.debug("failed to create {}: {}", elementTypeEnum.name(), elementName); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); - - eitherResult = Either.right(responseFormat); - break; - } else { - createdElementTypes.add(new ImmutablePair(elementType, false)); - } - } finally { - propertyOperation.getTitanGenericDao().rollback(); - } - } else { - propertyOperation.getTitanGenericDao().commit(); - createdElementTypes.add(new ImmutablePair(elementType, true)); - log.debug("{} : {} was created successfully.", elementTypeEnum.name(), elementName); - } - if (!elementTypeItr.hasNext()) { - log.info("all {} were created successfully!!!", elementTypeEnum.name()); - } - - } - } else { - - if (elementUpgrader != null) { - Either upgradeResponse = null; - try { - upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value()); - if (upgradeResponse.isRight()) { - StorageOperationStatus status = upgradeResponse.right().value(); - if (status == StorageOperationStatus.OK) { - createdElementTypes.add(new ImmutablePair(elementType, false)); - } else { - ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); - eitherResult = Either.right(responseFormat); - break; - } - } else { - log.debug("{} : {} was upgraded successfully.", elementTypeEnum.name(), elementName); - createdElementTypes.add(new ImmutablePair(elementType, true)); - } - } finally { - if (upgradeResponse == null || upgradeResponse.isRight()) { - propertyOperation.getTitanGenericDao().rollback(); - } else { - propertyOperation.getTitanGenericDao().commit(); - } - } - - } else { - // mshitrit Once GroupType Versions are supported add - // code here - createdElementTypes.add(new ImmutablePair(elementType, false)); - log.debug("{} : {} already exists.", elementTypeEnum.name(), elementName); - } - - } - - } - } finally { - if (eitherResult.isRight()) { - propertyOperation.getTitanGenericDao().rollback(); - } - } - - return eitherResult; - - } - - public Either>, ResponseFormat> createElementTypes(String elementTypesYml, Function, ActionStatus>> elementTypeFromYmlCreater, - Function, Either>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) { - - Either, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml); - if (elementTypes.isRight()) { - ActionStatus status = elementTypes.right().value(); - ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null); - return Either.right(responseFormat); - } - return elementTypeDaoCreater.apply(elementTypes.left().value()); - - } + private static final Logger log = LoggerFactory.getLogger(CommonImportManager.class); + + @Resource + private ComponentsUtils componentsUtils; + @Resource + private PropertyOperation propertyOperation; + + protected void setProperties(Map toscaJson, Consumer> consumer) { + consumer.accept(getProperties(toscaJson)); + } + + private List getProperties(Map toscaJson) { + List values = null; + Either, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson); + + if (properties.isLeft()) { + values = new ArrayList<>(); + Map propertiesMap = properties.left().value(); + if (propertiesMap != null && propertiesMap.isEmpty() == false) { + + for (Entry entry : propertiesMap.entrySet()) { + String propName = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition); + newPropertyDefinition.setName(propName); + values.add(newPropertyDefinition); + } + } + } + + return values; + } + + protected void setPropertiesMap(Map toscaJson, Consumer> consumer) { + final List properties = getProperties(toscaJson); + if (properties != null) { + Map collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e)); + consumer.accept(collect); + } + + } + + interface ICreateElementType { + ElementType createElement(T1 firstArg, T2 secondArg); + } + + protected Either, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType, ElementDefinition> createApi) { + + List elementTypes = new ArrayList<>(); + try { + Map toscaJson = (Map) new Yaml().load(elementTypesYml); + + elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson); + } catch (Exception e) { + log.debug("Failed to yaml file {}", elementTypesYml, e); + return Either.right(ActionStatus.INVALID_YAML_FILE); + } + return Either.left(elementTypes); + } + + /** + * @param createApi * @param createApi + * @param elementTypes + * @param toscaJson + */ + protected List createElementTypesFromToscaJsonMap( + ICreateElementType, ElementDefinition> createApi, Map toscaJson) { + List elementTypes = new ArrayList<>(); + + Iterator> elementTypesEntryItr = toscaJson.entrySet().iterator(); + while (elementTypesEntryItr.hasNext()) { + Entry elementTypeNameDataEntry = elementTypesEntryItr.next(); + String elementTypeName = elementTypeNameDataEntry.getKey(); + Map elementTypeJsonData = (Map) elementTypeNameDataEntry.getValue(); + ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData); + elementTypes.add(elementDefinition); + } + return elementTypes; + } + + protected void setField(Map toscaJson, String fieldName, Consumer setter) { + if (toscaJson.containsKey(fieldName)) { + FieldType fieldValue = (FieldType) toscaJson.get(fieldName); + setter.accept(fieldValue); + } + + } + + public enum ElementTypeEnum { + PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType + }; + + private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) { + ActionStatus ret; + switch (elementTypeEnum) { + case GroupType: + ret = componentsUtils.convertFromStorageResponseForGroupType(status); + break; + case DataType: + ret = componentsUtils.convertFromStorageResponseForDataType(status); + break; + case CapabilityType: + ret = componentsUtils.convertFromStorageResponseForCapabilityType(status); + break; + case InterfaceLifecycleType: + ret = componentsUtils.convertFromStorageResponseForLifecycleType(status); + break; + default: + ret = componentsUtils.convertFromStorageResponse(status); + break; + } + return ret; + } + + private ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) { + ResponseFormat ret; + switch (elementTypeEnum) { + case GroupType: + ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition); + break; + case PolicyType: + ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition); + break; + case DataType: + ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null); + break; + case CapabilityType: + ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition); + break; + + default: + ret = componentsUtils.getResponseFormat(actionStatus); + break; + } + return ret; + } + + protected Either>, ResponseFormat> createElementTypesByDao(List elementTypesToCreate, + Function> validator, Function> elementInfoGetter, + Function> elementFetcher, Function> elementAdder, + BiFunction> elementUpgrader) { + + List> createdElementTypes = new ArrayList<>(); + + Either>, ResponseFormat> eitherResult = Either.left(createdElementTypes); + + Iterator elementTypeItr = elementTypesToCreate.iterator(); + + try { + + while (elementTypeItr.hasNext()) { + ElementTypeDefinition elementType = elementTypeItr.next(); + final ImmutablePair elementInfo = elementInfoGetter.apply(elementType); + ElementTypeEnum elementTypeEnum = elementInfo.left; + String elementName = elementInfo.right; + + Either validateElementType = validator.apply(elementType); + if (validateElementType.isRight()) { + ResponseFormat responseFormat = validateElementType.right().value(); + log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage()); + eitherResult = Either.right(responseFormat); + break; + } + + log.info("send {} : {} to dao for create", elementTypeEnum, elementName); + + Either findElementType = elementFetcher.apply(elementName); + if (findElementType.isRight()) { + StorageOperationStatus status = findElementType.right().value(); + log.debug("searched {} finished with result:{}", elementTypeEnum, status.name()); + if (status != StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType); + eitherResult = Either.right(responseFormat); + break; + } else { + Either dataModelResponse = elementAdder.apply(elementType); + + if (dataModelResponse.isRight()) { + try { + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name()); + log.debug("failed to create {}: {}", elementTypeEnum, elementName); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + + eitherResult = Either.right(responseFormat); + break; + } else { + createdElementTypes.add(new ImmutablePair(elementType, false)); + } + } finally { + propertyOperation.getTitanGenericDao().rollback(); + } + } else { + propertyOperation.getTitanGenericDao().commit(); + createdElementTypes.add(new ImmutablePair(elementType, true)); + log.debug("{} : {} was created successfully.", elementTypeEnum, elementName); + } + if (!elementTypeItr.hasNext()) { + log.info("all {} were created successfully!!!", elementTypeEnum); + } + + } + } else { + + if (elementUpgrader != null) { + Either upgradeResponse = null; + try { + upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value()); + if (upgradeResponse.isRight()) { + StorageOperationStatus status = upgradeResponse.right().value(); + if (status == StorageOperationStatus.OK) { + createdElementTypes.add(new ImmutablePair(elementType, false)); + } else { + ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType); + eitherResult = Either.right(responseFormat); + break; + } + } else { + log.debug("{} : {} was upgraded successfully.", elementTypeEnum, elementName); + createdElementTypes.add(new ImmutablePair(elementType, true)); + } + } finally { + if (upgradeResponse == null || upgradeResponse.isRight()) { + propertyOperation.getTitanGenericDao().rollback(); + } else { + propertyOperation.getTitanGenericDao().commit(); + } + } + + } else { + // mshitrit Once GroupType Versions are supported add + // code here + createdElementTypes.add(new ImmutablePair(elementType, false)); + log.debug("{} : {} already exists.", elementTypeEnum, elementName); + } + + } + + } + } finally { + if (eitherResult.isRight()) { + propertyOperation.getTitanGenericDao().rollback(); + } + } + + return eitherResult; + + } + + public Either>, ResponseFormat> createElementTypes(String elementTypesYml, Function, ActionStatus>> elementTypeFromYmlCreater, + Function, Either>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) { + + Either, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml); + if (elementTypes.isRight()) { + ActionStatus status = elementTypes.right().value(); + ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null); + return Either.right(responseFormat); + } + return elementTypeDaoCreater.apply(elementTypes.left().value()); + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index 40e67aa876..4688aa4b8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -42,31 +35,17 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; -import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapReqDef; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.utils.CommonBeUtils; @@ -79,1070 +58,1077 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; public abstract class ComponentBusinessLogic extends BaseBusinessLogic { - @Autowired - protected ArtifactsBusinessLogic artifactsBusinessLogic; - - @Autowired - protected ComponentCache componentCache; - - @Autowired - private GenericTypeBusinessLogic genericTypeBusinessLogic; - - public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { - this.genericTypeBusinessLogic = genericTypeBusinessLogic; - } - - private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName()); - - private static final String TAG_FIELD_LABEL = "tag"; - - public abstract Either, ResponseFormat> deleteMarkedComponents(); - - public abstract ComponentInstanceBusinessLogic getComponentInstanceBL(); - - public abstract Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText); - - /** - * - * @param componentId - * @param dataParamsToReturn - * @return - */ - public abstract Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn); - - protected Either validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { - Either userValidationResult = validateUserNotEmpty(user, ecompErrorContext); - ResponseFormat responseFormat; - if (userValidationResult.isRight()) { - user.setUserId("UNKNOWN"); - responseFormat = userValidationResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType()); - return Either.right(responseFormat); - } - Either userResult = validateUserExists(user, ecompErrorContext, inTransaction); - if (userResult.isRight()) { - responseFormat = userResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType()); - return Either.right(responseFormat); - } - return userResult; - } - - protected Either validateUserRole(User user, Component component, List roles, AuditingActionEnum auditAction, String comment) { - if (roles != null && roles.isEmpty()) { - roles.add(Role.ADMIN); - roles.add(Role.DESIGNER); - } - Either validationResult = validateUserRole(user, roles); - if (validationResult.isRight()) { - ComponentTypeEnum componentType = component.getComponentType(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - if (componentType.equals(ComponentTypeEnum.SERVICE)) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - String distributionStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, distributionStatus); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, distributionStatus); - } - componentsUtils.auditComponent(validationResult.right().value(), user, component, "", "", auditAction, componentType, additionalParams); - } - return validationResult; - } - - protected Either validateComponentName(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String componentName = component.getName(); - if (!ValidationUtils.validateStringNotEmpty(componentName)) { - log.debug("component name is empty"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateComponentNameLength(componentName)) { - log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - if (!validateTagPattern(componentName)) { - log.debug("Component name {} has invalid format", componentName); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); - component.setSystemName(ValidationUtils.convertToSystemName(componentName)); - - return Either.left(true); - } - - protected Either validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - String description = component.getDescription(); - if (!ValidationUtils.validateStringNotEmpty(description)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - description = cleanUpText(description); - Either validatDescription = validateComponentDescription(description, type); - if (validatDescription.isRight()) { - ResponseFormat responseFormat = validatDescription.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - return Either.right(responseFormat); - } - component.setDescription(description); - return Either.left(true); - } - - public Either validateComponentDescription(String description, ComponentTypeEnum type) { - if (description != null) { - if (!ValidationUtils.validateDescriptionLength(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); - } - - if (!ValidationUtils.validateIsEnglish(description)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue())); - } - return Either.left(true); - } - return Either.left(false); - } - - protected Either validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { - ComponentTypeEnum type = component.getComponentType(); - ResourceTypeEnum resourceType = null; - if(component instanceof Resource){ - resourceType = ((Resource)component).getResourceType(); - } - Either dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); - - if (dataModelResponse.isLeft()) { - if ( !dataModelResponse.left().value()) { - return Either.left(true); - } else { - log.info("Component with name {} already exists", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - } - BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); - log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - protected Either validateContactId(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate component contactId"); - ComponentTypeEnum type = component.getComponentType(); - String contactId = component.getContactId(); - - if (!ValidationUtils.validateStringNotEmpty(contactId)) { - log.info("contact is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - Either validateContactIdResponse = validateContactId(contactId, type); - if (validateContactIdResponse.isRight()) { - ResponseFormat responseFormat = validateContactIdResponse.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - } - return validateContactIdResponse; - } - - private Either validateContactId(String contactId, ComponentTypeEnum type) { - if (contactId != null) { - if (!ValidationUtils.validateContactId(contactId)) { - log.info("contact is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - - public Either validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { - log.trace("validate conformance level"); - - if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.error("conformance level validation for non service component, id {}", componentUuid); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(errorResponse); - } - - Either resp = validateUserExists(userId, "validateConformanceLevel", false); - if (resp.isRight()) { - log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); - return Either.right(resp.right().value()); - } - - Either eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); - if (eitherComponent.isRight()) { - log.error("can't validate conformance level, component not found, uuid {}", componentUuid); - BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); - - StorageOperationStatus status = eitherComponent.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); - return Either.right(responseFormat); - } - - String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); - if (StringUtils.isBlank(componentConformanceLevel)) { - log.error("component conformance level property is null or empty, uuid {}", componentUuid); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(errorResponse); - } - - String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); - Boolean result = true; - if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { - log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); - result = false; - } - log.trace("conformance level validation finished"); - - return Either.left(result); - } - - protected Either validateIcon(User user, Component component, AuditingActionEnum actionEnum) { - log.debug("validate Icon"); - ComponentTypeEnum type = component.getComponentType(); - String icon = component.getIcon(); - if (!ValidationUtils.validateStringNotEmpty(icon)) { - log.info("icon is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type); - return Either.right(errorResponse); - } - - Either validateIcon = validateIcon(icon, type); - if (validateIcon.isRight()) { - ResponseFormat responseFormat = validateIcon.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type); - } - return validateIcon; - } - - private Either validateIcon(String icon, ComponentTypeEnum type) { - if (icon != null) { - if (!ValidationUtils.validateIconLength(icon)) { - log.debug("icon exceeds max length"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); - } - - if (!ValidationUtils.validateIcon(icon)) { - log.info("icon is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - protected Either validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) { - List tagsList = component.getTags(); - - Either validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType()); - if (validateTags.isRight()) { - ResponseFormat responseFormat = validateTags.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType()); - return Either.right(responseFormat); - } - ValidationUtils.removeDuplicateFromList(tagsList); - return Either.left(true); - } - - protected Either validateComponentTags(List tags, String name, ComponentTypeEnum componentType) { - log.debug("validate component tags"); - boolean includesComponentName = false; - int tagListSize = 0; - if (tags != null && !tags.isEmpty()) { - for (String tag : tags) { - if (!ValidationUtils.validateTagLength(tag)) { - log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); - } - if (validateTagPattern(tag)) { - if (!includesComponentName) { - includesComponentName = name.equals(tag); - } - } else { - log.debug("invalid tag {}", tag); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL)); - } - tagListSize += tag.length() + 1; - } - if (tagListSize > 0) { - tagListSize--; - } - - if (!includesComponentName) { - log.debug("tags must include component name"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME)); - } - if (!ValidationUtils.validateTagListLength(tagListSize)) { - log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); - } - return Either.left(true); - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS)); - } - - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateComponentNamePattern(tag); - } - - protected Either validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) { - if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { - return Either.left(true); - } - log.debug("validate ProjectCode name "); - String projectCode = component.getProjectCode(); - - if (!ValidationUtils.validateStringNotEmpty(projectCode)) { - log.info("projectCode is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE); - componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, component.getComponentType()); - return Either.right(errorResponse); - } - - Either validateProjectCodeResponse = validateProjectCode(projectCode); - if (validateProjectCodeResponse.isRight()) { - ResponseFormat responseFormat = validateProjectCodeResponse.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType()); - } - return validateProjectCodeResponse; - - } - - private Either validateProjectCode(String projectCode) { - if (projectCode != null) { - if (!ValidationUtils.validateProjectCode(projectCode)) { - log.info("projectCode is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - } - - protected void checkComponentFieldsForOverrideAttempt(Component component) { - if (component.getLifecycleState() != null) { - log.info("LifecycleState cannot be defined by user. This field will be overridden by the application"); - } - if (component.getVersion() != null) { - log.info("Version cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getCreatorUserId() != null) || (component.getCreatorFullName() != null)) { - log.info("Creator cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getLastUpdaterUserId() != null) || (component.getLastUpdaterFullName() != null)) { - log.info("Last Updater cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getCreationDate() != null)) { - log.info("Creation Date cannot be defined by user. This field will be overridden by the application"); - } - if ((component.isHighestVersion() != null)) { - log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getUUID() != null)) { - log.info("UUID cannot be defined by user. This field will be overridden by the application"); - } - if ((component.getLastUpdateDate() != null)) { - log.info("Last Update Date cannot be defined by user. This field will be overridden by the application"); - } - if (component.getUniqueId() != null) { - log.info("uid cannot be defined by user. This field will be overridden by the application."); - component.setUniqueId(null); - } - if (component.getInvariantUUID() != null) { - log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application."); - } - } - - protected Either validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) { - // validate component name uniqueness - log.debug("validate component name "); - Either componentNameValidation = validateComponentName(user, component, actionEnum); - if (componentNameValidation.isRight()) { - return componentNameValidation; - } - - // validate description - log.debug("validate description"); - Either descValidation = validateDescriptionAndCleanup(user, component, actionEnum); - if (descValidation.isRight()) { - return descValidation; - } - - // validate tags - log.debug("validate tags"); - Either tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum); - if (tagsValidation.isRight()) { - return tagsValidation; - } - - // validate contact info - log.debug("validate contact info"); - Either contactIdValidation = validateContactId(user, component, actionEnum); - if (contactIdValidation.isRight()) { - return contactIdValidation; - } - - // validate icon - log.debug("validate icon"); - Either iconValidation = validateIcon(user, component, actionEnum); - if (iconValidation.isRight()) { - return iconValidation; - } - return Either.left(true); - } - - public Either getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { - - Either resp = validateUserExists(userId, "create Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either eitherRet = null; - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreRequirements(false); - filter.setIgnoreComponentInstances(false); - Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); - if (eitherComponent.isLeft()) { - eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); - } else { - BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); - eitherRet = Either.right(eitherComponent.right().value()); - } - return eitherRet; - } - - public Either, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids, - String userId) { - ResponseFormat responseFormat = null; - try{ - Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - - if (resp.isLeft()) { - List result = new ArrayList<>(); - List componentsUidToFetch = new ArrayList<>(); - componentsUidToFetch.addAll(componentUids); - - if (!componentsUidToFetch.isEmpty()) { - log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); - Boolean isHighest = isHighest(highestFilter); - Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - result.addAll(nonCheckoutCompResponse.left().value()); - } else { - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); - } - } - return Either.left(result); - } else { - responseFormat = resp.right().value(); - } - } - finally{ - titanDao.commit(); - } - return Either.right(responseFormat); - } - - private Boolean isHighest(HighestFilterEnum highestFilter) { - Boolean isHighest = null; - switch (highestFilter) { - case ALL: - break; - case HIGHEST_ONLY: - isHighest = true; - break; - case NON_HIGHEST_ONLY: - isHighest = false; - break; - default: - break; - } - return isHighest; - } - - public Either, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { - ResponseFormat responseFormat = null; - - try{ - Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); - if (resp.isLeft()) { - - Boolean isHighest = isHighest(highestFilter); - Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); - - if (nonCheckoutCompResponse.isLeft()) { - log.debug("Retrived Resource successfully."); - return Either.left(nonCheckoutCompResponse.left().value()); - } - responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); - } else { - responseFormat = resp.right().value(); - } - } finally { - titanDao.commit(); - } - return Either.right(responseFormat); - } - - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - - } - - @SuppressWarnings("unchecked") - public void setToscaArtifactsPlaceHolders(Component component, User user) { - Map artifactMap = component.getToscaArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap<>(); - } - String componentUniqueId = component.getUniqueId(); - String componentSystemName = component.getSystemName(); - String componentType = component.getComponentType().getValue().toLowerCase(); - Map toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts(); - - if (toscaArtifacts != null) { - for (Entry artifactInfoMap : toscaArtifacts.entrySet()) { - Map artifactInfo = (Map) artifactInfoMap.getValue(); - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA); - artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName"))); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - component.setToscaArtifacts(artifactMap); - } - - public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { - return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); - } - - public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { - Either toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); - if ( toscaElement.isRight() ){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); - return Either.right(response); - } - component = toscaElement.left().value(); - Either, ResponseFormat> generateToscaRes = null; - if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { - ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) - .findAny().get(); - generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); - if (generateToscaRes.isRight()) { - return generateToscaRes; - } - toscaArtifact = generateToscaRes.left().value().left().value(); - component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); - if(!isAbstractResource(component)){ - toscaArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) - .findAny().get(); - generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); - if (generateToscaRes.isRight()) { - return generateToscaRes; - } - toscaArtifact = generateToscaRes.left().value().left().value(); - component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); - } - } - return generateToscaRes; - } - - private boolean isAbstractResource(Component component) { - return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); - } - - public Either, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, - boolean inTransaction, boolean fetchTemplatesFromDB) { - return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); - } - - public Either, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap additionalParam) { - - Map additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); - - if (latestVersionEither.isRight()) { - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); - return Either.right(response); - } - - List components = latestVersionEither.left().value(); - - Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); - if(component == null){ - component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); - } - - if(component == null){ - ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); - return Either.right(response); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - // TODO remove after migration - handle artifact not found(no - // placeholder) - if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); - } - ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() - .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) - .findAny().get(); - return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact); - } - - protected StorageOperationStatus markComponentToDelete(Component component) { - - ComponentTypeEnum componentType = component.getComponentType(); - String uniqueId = component.getUniqueId(); - if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) { - log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType); - return StorageOperationStatus.NOT_FOUND; - } - - StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component); - if (StorageOperationStatus.OK != markResourceToDelete) { - log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete); - return markResourceToDelete; - } else { - log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); - return StorageOperationStatus.OK; - } - } - - public Either validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) { - String descriptionUpdated = updatedComponent.getDescription(); - String descriptionCurrent = currentComponent.getDescription(); - if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) { - Either validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction); - if (validateDescriptionResponse.isRight()) { - ResponseFormat errorRespons = validateDescriptionResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setDescription(updatedComponent.getDescription()); - } - return Either.left(true); - } - - public Either validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) { - String projectCodeUpdated = updatedComponent.getProjectCode(); - String projectCodeCurrent = currentComponent.getProjectCode(); - if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) { - Either validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setProjectCode(updatedComponent.getProjectCode()); - } - return Either.left(true); - } - - public Either validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) { - String iconUpdated = updatedComponent.getIcon(); - String iconCurrent = currentComponent.getIcon(); - if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either validatIconResponse = validateIcon(user, updatedComponent, null); - if (validatIconResponse.isRight()) { - ResponseFormat errorRespons = validatIconResponse.right().value(); - return Either.right(errorRespons); - } - currentComponent.setIcon(updatedComponent.getIcon()); - } else { - log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase()); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - protected Either, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { - - log.trace("start deleteMarkedComponents"); - Either, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); - - titanDao.commit(); - if ( deleteMarkedElements.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); - return Either.right(responseFormat); - } - log.trace("end deleteMarkedComponents"); - return Either.left(deleteMarkedElements.left().value()); - } - - public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) { - List artifacts = new ArrayList<>(); - Either, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); - if (artifactsResponse.isRight()) { - if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); - return Either.right(artifactsResponse.right().value()); - } - } else { - artifacts.addAll(artifactsResponse.left().value().values()); - } - return Either.left(artifacts); - } - - /** - * - * @param componentId - * @param user - * @param dataParamsToReturn - ui list of params to return - * @return - */ - - public Either getComponentDataFilteredByParams(String componentId, User user, List dataParamsToReturn) { - - if (user != null) { - Either eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - } - - UiComponentDataTransfer result = new UiComponentDataTransfer(); - - if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { - Either.left(result); - - } else { - Either uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); - if(uiDataTransferEither.isRight()){ - return Either.right(uiDataTransferEither.right().value()); - } - result = uiDataTransferEither.left().value(); - } - - return Either.left(result); - } - - protected void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) { - List genericAndComponentInputs = new ArrayList<>(); - List genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); - genericAndComponentInputs.addAll(genericInputs); - if (null != component.getInputs()){ - List nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); - genericAndComponentInputs.addAll(nonGenericInputsFromComponent); - } - component.setInputs(genericAndComponentInputs); - } - - private List getAllNonGenericInputsFromComponent(List genericInputs, List componentInputs) { - if (genericInputs == null) { - return componentInputs; - } - - Map inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); - List componentNonGenericInputs = new ArrayList<>(); - componentInputs.stream().forEach(input -> { - if (!inputByNameMap.containsKey(input.getName())) { - componentNonGenericInputs.add(input); - } - }); - return componentNonGenericInputs; - } - - protected Either fetchAndSetDerivedFromGenericType(T component){ - Either genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); - if(genericTypeEither.isRight()){ - log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType())); - } - Resource genericTypeResource = genericTypeEither.left().value(); - component.setDerivedFromGenericInfo(genericTypeResource); - return Either.left(genericTypeResource); - } - - public Either>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map> filters, String userId) { - Either>, ResponseFormat> response = null; - Either getResourceRes = null; - try{ - if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){ - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (userId != null && response == null) { - Either validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false); - if (validateUserRes.isRight()) { - response = Either.right(validateUserRes.right().value()); - } - } - if(response == null){ - getResourceRes = toscaOperationFacade.getToscaElement(componentId); - if(getResourceRes.isRight()){ - response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); - } - } - if(response == null){ - response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); - } - } catch(Exception e){ - log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId); - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally{ - if (response.isLeft()){ - toscaOperationFacade.commit(); - } else { - toscaOperationFacade.rollback(); - } - } - return response; - } - - private Either>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map> filters) { - - Map> filteredProperties = new HashMap<>(); - Either>, ResponseFormat> result = Either.left(filteredProperties); - List filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE)); - String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0); - boolean searchByFragment = propertyNameFragment.length() > 3 ; - if(CollectionUtils.isNotEmpty(filteredInstances)){ - for(ComponentInstance instance : filteredInstances){ - if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ - List currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); - if(CollectionUtils.isNotEmpty(currProperties)){ - filteredProperties.put(instance.getUniqueId(), currProperties); - } - } - if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ - List currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); - if(CollectionUtils.isNotEmpty(currInputs)){ - if(filteredProperties.get(instance.getUniqueId())!=null){ - filteredProperties.get(instance.getUniqueId()).addAll(currInputs); - } else { - filteredProperties.put(instance.getUniqueId(), currInputs); - } - } - } - } - } - return result; - } - - private List getFilteredComponentInstanceInputs(List inputs, String propertyNameFragment, boolean searchByFragment) { - return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); - } - - private List getFilteredComponentInstanceProperties(List instanceProperties, String propertyNameFragment, boolean searchByFragment) { - return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); - } - - private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) { - boolean isMatching = false; - if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){ - isMatching = true; - } - if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ - isMatching = true; - } - return isMatching; - } - - private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { - boolean isMatching = false; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ - isMatching = true; - } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ - isMatching = true; - } - if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ - isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); - } - return isMatching; - } - - private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { - String propertyType; - List dataTypeProperties; - DataTypeDefinition currentProperty; - if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ - return true; - } - if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ - return true; - } - - propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); - - if(ToscaPropertyType.isScalarType(propertyType)){ - return false; - } - Either getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); - if(getDataTypeByNameRes.isRight()){ - return false; - } - currentProperty = getDataTypeByNameRes.left().value(); - dataTypeProperties = currentProperty.getProperties(); - - if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } - } - } - dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); - if(CollectionUtils.isNotEmpty(dataTypeProperties)){ - for(PropertyDefinition prop : dataTypeProperties){ - if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ - return true; - } - } - } - return false; - } - - private boolean isEmptyInnerType(PropertyDataDefinition property) { - return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; - } - - public Either shouldUpgradeToLatestGeneric(Component clonedComponent) { - - if(!clonedComponent.deriveFromGeneric()) - return Either.left(false); - Boolean shouldUpgrade = false; - String currentGenericType = clonedComponent.getDerivedFromGenericType(); - String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); - Either fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent); - if(fetchAndSetLatestGeneric.isRight()) - return Either.right(fetchAndSetLatestGeneric.right().value()); - Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); - if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ - shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); - if(!shouldUpgrade) { - reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); - } - } - return Either.left(shouldUpgrade); - } - - private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) { - clonedComponent.setDerivedFromGenericType(currentGenericType); - clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); - } - - private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { - Map currentMap = ToscaDataDefinition.listToMapByName(currentList); - Map upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); - return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); - } - - private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ - - List genericTypeProps = latestGeneric.getProperties(); - Either, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); - if (validMerge.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); - return false; - } - List genericTypeAttributes = latestGeneric.getAttributes(); - validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); - if (validMerge.isRight()) { - log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); - return false; - } - return true; - } - + @Autowired + protected ArtifactsBusinessLogic artifactsBusinessLogic; + + @Autowired + protected ComponentCache componentCache; + + @Autowired + private GenericTypeBusinessLogic genericTypeBusinessLogic; + + public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) { + this.genericTypeBusinessLogic = genericTypeBusinessLogic; + } + + private static final Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class); + + private static final String TAG_FIELD_LABEL = "tag"; + + public abstract Either, ResponseFormat> deleteMarkedComponents(); + + public abstract ComponentInstanceBusinessLogic getComponentInstanceBL(); + + public abstract Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText); + + /** + * + * @param componentId + * @param dataParamsToReturn + * @return + */ + public abstract Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn); + + protected Either validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) { + Either userValidationResult = validateUserNotEmpty(user, ecompErrorContext); + ResponseFormat responseFormat; + if (userValidationResult.isRight()) { + user.setUserId("UNKNOWN"); + responseFormat = userValidationResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); + return Either.right(responseFormat); + } + Either userResult = validateUserExists(user, ecompErrorContext, inTransaction); + if (userResult.isRight()) { + responseFormat = userResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType()); + return Either.right(responseFormat); + } + return userResult; + } + + protected Either validateUserRole(User user, Component component, List roles, AuditingActionEnum auditAction, String comment) { + if (roles != null && roles.isEmpty()) { + roles.add(Role.ADMIN); + roles.add(Role.DESIGNER); + } + Either validationResult = validateUserRole(user, roles); + if (validationResult.isRight()) { + String commentStr = null; + String distrStatus = null; + ComponentTypeEnum componentType = component.getComponentType(); + if (componentType.equals(ComponentTypeEnum.SERVICE)) { + distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus(); + commentStr = comment; + } + componentsUtils.auditComponent(validationResult.right().value(), user, component, auditAction, componentType, + ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(), + ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(), + null, commentStr, null, null); + + + } + return validationResult; + } + + protected Either validateComponentName(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + String componentName = component.getName(); + if (!ValidationUtils.validateStringNotEmpty(componentName)) { + log.debug("component name is empty"); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateComponentNameLength(componentName)) { + log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + if (!validateTagPattern(componentName)) { + log.debug("Component name {} has invalid format", componentName); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName)); + component.setSystemName(ValidationUtils.convertToSystemName(componentName)); + + return Either.left(true); + } + + protected Either validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + String description = component.getDescription(); + if (!ValidationUtils.validateStringNotEmpty(description)) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + description = cleanUpText(description); + Either validatDescription = validateComponentDescription(description, type); + if (validatDescription.isRight()) { + ResponseFormat responseFormat = validatDescription.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + return Either.right(responseFormat); + } + component.setDescription(description); + return Either.left(true); + } + + public Either validateComponentDescription(String description, ComponentTypeEnum type) { + if (description != null) { + if (!ValidationUtils.validateDescriptionLength(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); + } + + if (!ValidationUtils.validateIsEnglish(description)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue())); + } + return Either.left(true); + } + return Either.left(false); + } + + protected Either validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) { + ComponentTypeEnum type = component.getComponentType(); + ResourceTypeEnum resourceType = null; + if(component instanceof Resource){ + resourceType = ((Resource)component).getResourceType(); + } + Either dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type); + + if (dataModelResponse.isLeft()) { + if ( !dataModelResponse.left().value()) { + return Either.left(true); + } else { + log.info("Component with name {} already exists", component.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + } + BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique"); + log.debug("Error while validateComponentNameUnique for component: {}", component.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + protected Either validateContactId(User user, Component component, AuditingActionEnum actionEnum) { + log.debug("validate component contactId"); + ComponentTypeEnum type = component.getComponentType(); + String contactId = component.getContactId(); + + if (!ValidationUtils.validateStringNotEmpty(contactId)) { + log.info("contact is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + Either validateContactIdResponse = validateContactId(contactId, type); + if (validateContactIdResponse.isRight()) { + ResponseFormat responseFormat = validateContactIdResponse.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + } + return validateContactIdResponse; + } + + private Either validateContactId(String contactId, ComponentTypeEnum type) { + if (contactId != null) { + if (!ValidationUtils.validateContactId(contactId)) { + log.info("contact is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue()); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + + public Either validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { + log.trace("validate conformance level"); + + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { + log.error("conformance level validation for non service component, id {}", componentUuid); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(errorResponse); + } + + Either resp = validateUserExists(userId, "validateConformanceLevel", false); + if (resp.isRight()) { + log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); + return Either.right(resp.right().value()); + } + + Either eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); + if (eitherComponent.isRight()) { + log.error("can't validate conformance level, component not found, uuid {}", componentUuid); + BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); + + StorageOperationStatus status = eitherComponent.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Either.right(responseFormat); + } + + String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); + if (StringUtils.isBlank(componentConformanceLevel)) { + log.error("component conformance level property is null or empty, uuid {}", componentUuid); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponse); + } + + String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); + Boolean result = true; + if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { + log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); + result = false; + } + log.trace("conformance level validation finished"); + + return Either.left(result); + } + + protected Either validateIcon(User user, Component component, AuditingActionEnum actionEnum) { + log.debug("validate Icon"); + ComponentTypeEnum type = component.getComponentType(); + String icon = component.getIcon(); + if (!ValidationUtils.validateStringNotEmpty(icon)) { + log.info("icon is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type); + return Either.right(errorResponse); + } + + Either validateIcon = validateIcon(icon, type); + if (validateIcon.isRight()) { + ResponseFormat responseFormat = validateIcon.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type); + } + return validateIcon; + } + + private Either validateIcon(String icon, ComponentTypeEnum type) { + if (icon != null) { + if (!ValidationUtils.validateIconLength(icon)) { + log.debug("icon exceeds max length"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); + } + + if (!ValidationUtils.validateIcon(icon)) { + log.info("icon is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue()); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + protected Either validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) { + List tagsList = component.getTags(); + + Either validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType()); + if (validateTags.isRight()) { + ResponseFormat responseFormat = validateTags.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType()); + return Either.right(responseFormat); + } + ValidationUtils.removeDuplicateFromList(tagsList); + return Either.left(true); + } + + protected Either validateComponentTags(List tags, String name, ComponentTypeEnum componentType) { + log.debug("validate component tags"); + boolean includesComponentName = false; + int tagListSize = 0; + if (tags != null && !tags.isEmpty()) { + for (String tag : tags) { + if (!ValidationUtils.validateTagLength(tag)) { + log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); + } + if (validateTagPattern(tag)) { + if (!includesComponentName) { + includesComponentName = name.equals(tag); + } + } else { + log.debug("invalid tag {}", tag); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL)); + } + tagListSize += tag.length() + 1; + } + if (tagListSize > 0) { + tagListSize--; + } + + if (!includesComponentName) { + log.debug("tags must include component name"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME)); + } + if (!ValidationUtils.validateTagListLength(tagListSize)) { + log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); + } + return Either.left(true); + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS)); + } + + protected boolean validateTagPattern(String tag) { + return ValidationUtils.validateComponentNamePattern(tag); + } + + protected Either validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) { + if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { + return Either.left(true); + } + log.debug("validate ProjectCode name "); + String projectCode = component.getProjectCode(); + + if (!ValidationUtils.validateStringNotEmpty(projectCode)) { + log.info("projectCode is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE); + componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build()); + return Either.right(errorResponse); + } + + Either validateProjectCodeResponse = validateProjectCode(projectCode); + if (validateProjectCodeResponse.isRight()) { + ResponseFormat responseFormat = validateProjectCodeResponse.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build()); + } + return validateProjectCodeResponse; + + } + + private Either validateProjectCode(String projectCode) { + if (projectCode != null) { + if (!ValidationUtils.validateProjectCode(projectCode)) { + log.info("projectCode is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + } + + protected void checkComponentFieldsForOverrideAttempt(Component component) { + if (component.getLifecycleState() != null) { + log.info("LifecycleState cannot be defined by user. This field will be overridden by the application"); + } + if (component.getVersion() != null) { + log.info("Version cannot be defined by user. This field will be overridden by the application"); + } + if (component.getCreatorUserId() != null || component.getCreatorFullName() != null) { + log.info("Creator cannot be defined by user. This field will be overridden by the application"); + } + if (component.getLastUpdaterUserId() != null || component.getLastUpdaterFullName() != null) { + log.info("Last Updater cannot be defined by user. This field will be overridden by the application"); + } + if (component.getCreationDate() != null) { + log.info("Creation Date cannot be defined by user. This field will be overridden by the application"); + } + if (component.isHighestVersion() != null) { + log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application"); + } + if (component.getUUID() != null) { + log.info("UUID cannot be defined by user. This field will be overridden by the application"); + } + if (component.getLastUpdateDate() != null) { + log.info("Last Update Date cannot be defined by user. This field will be overridden by the application"); + } + if (component.getUniqueId() != null) { + log.info("uid cannot be defined by user. This field will be overridden by the application."); + component.setUniqueId(null); + } + if (component.getInvariantUUID() != null) { + log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application."); + } + } + + protected Either validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) { + // validate component name uniqueness + log.debug("validate component name "); + Either componentNameValidation = validateComponentName(user, component, actionEnum); + if (componentNameValidation.isRight()) { + return componentNameValidation; + } + + // validate description + log.debug("validate description"); + Either descValidation = validateDescriptionAndCleanup(user, component, actionEnum); + if (descValidation.isRight()) { + return descValidation; + } + + // validate tags + log.debug("validate tags"); + Either tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum); + if (tagsValidation.isRight()) { + return tagsValidation; + } + + // validate contact info + log.debug("validate contact info"); + Either contactIdValidation = validateContactId(user, component, actionEnum); + if (contactIdValidation.isRight()) { + return contactIdValidation; + } + + // validate icon + log.debug("validate icon"); + Either iconValidation = validateIcon(user, component, actionEnum); + if (iconValidation.isRight()) { + return iconValidation; + } + return Either.left(true); + } + + public Either getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + + Either resp = validateUserExists(userId, "create Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either eitherRet = null; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreComponentInstances(false); + Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); + if (eitherComponent.isLeft()) { + eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities())); + } else { + BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId); + eitherRet = Either.right(eitherComponent.right().value()); + } + return eitherRet; + } + + public Either, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List componentUids, + String userId) { + ResponseFormat responseFormat = null; + try{ + Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + + if (resp.isLeft()) { + List result = new ArrayList<>(); + List componentsUidToFetch = new ArrayList<>(); + componentsUidToFetch.addAll(componentUids); + + if (!componentsUidToFetch.isEmpty()) { + log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size()); + Boolean isHighest = isHighest(highestFilter); + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + result.addAll(nonCheckoutCompResponse.left().value()); + } else { + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } + } + return Either.left(result); + } else { + responseFormat = resp.right().value(); + } + } + finally{ + titanDao.commit(); + } + return Either.right(responseFormat); + } + + private Boolean isHighest(HighestFilterEnum highestFilter) { + Boolean isHighest = null; + switch (highestFilter) { + case ALL: + break; + case HIGHEST_ONLY: + isHighest = true; + break; + case NON_HIGHEST_ONLY: + isHighest = false; + break; + default: + break; + } + return isHighest; + } + + public Either, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) { + ResponseFormat responseFormat = null; + + try{ + Either resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false); + if (resp.isLeft()) { + + Boolean isHighest = isHighest(highestFilter); + Either, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType); + + if (nonCheckoutCompResponse.isLeft()) { + log.debug("Retrived Resource successfully."); + return Either.left(nonCheckoutCompResponse.left().value()); + } + responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())); + } else { + responseFormat = resp.right().value(); + } + } finally { + titanDao.commit(); + } + return Either.right(responseFormat); + } + + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + + } + + @SuppressWarnings("unchecked") + public void setToscaArtifactsPlaceHolders(Component component, User user) { + Map artifactMap = component.getToscaArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap<>(); + } + String componentUniqueId = component.getUniqueId(); + String componentSystemName = component.getSystemName(); + String componentType = component.getComponentType().getValue().toLowerCase(); + Map toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts(); + + if (toscaArtifacts != null) { + for (Entry artifactInfoMap : toscaArtifacts.entrySet()) { + Map artifactInfo = (Map) artifactInfoMap.getValue(); + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA); + artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName"))); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + component.setToscaArtifacts(artifactMap); + } + + public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) { + return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true); + } + + public Either, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) { + Either toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId()); + if ( toscaElement.isRight() ){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType())); + return Either.right(response); + } + component = toscaElement.left().value(); + Either, ResponseFormat> generateToscaRes = null; + if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) { + ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())) + .findAny().get(); + generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); + if (generateToscaRes.isRight()) { + return generateToscaRes; + } + toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); + if(!isAbstractResource(component)){ + toscaArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); + generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true); + if (generateToscaRes.isRight()) { + return generateToscaRes; + } + toscaArtifact = generateToscaRes.left().value().left().value(); + component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact); + } + } + return generateToscaRes; + } + + private boolean isAbstractResource(Component component) { + return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract(); + } + + public Either, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock, + boolean inTransaction, boolean fetchTemplatesFromDB) { + return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB); + } + + public Either, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap additionalParam) { + + Either, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null); + + if (latestVersionEither.isRight()) { + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType)); + return Either.right(response); + } + + List components = latestVersionEither.left().value(); + + Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null); + if(component == null){ + component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null); + } + + if(component == null){ + ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)); + return Either.right(response); + } + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + // TODO remove after migration - handle artifact not found(no + // placeholder) + if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name())); + } + ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream() + .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) + .findAny().get(); + return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact); + } + + protected StorageOperationStatus markComponentToDelete(Component component) { + + ComponentTypeEnum componentType = component.getComponentType(); + String uniqueId = component.getUniqueId(); + if (Boolean.TRUE.equals(component.getIsDeleted())) { + log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType); + return StorageOperationStatus.NOT_FOUND; + } + + StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component); + if (StorageOperationStatus.OK != markResourceToDelete) { + log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete); + return markResourceToDelete; + } else { + log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType); + return StorageOperationStatus.OK; + } + } + + public Either validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) { + String descriptionUpdated = updatedComponent.getDescription(); + String descriptionCurrent = currentComponent.getDescription(); + if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) { + Either validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction); + if (validateDescriptionResponse.isRight()) { + ResponseFormat errorRespons = validateDescriptionResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setDescription(updatedComponent.getDescription()); + } + return Either.left(true); + } + + public Either validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) { + String projectCodeUpdated = updatedComponent.getProjectCode(); + String projectCodeCurrent = currentComponent.getProjectCode(); + if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) { + Either validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null); + if (validatProjectCodeResponse.isRight()) { + ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setProjectCode(updatedComponent.getProjectCode()); + } + return Either.left(true); + } + + public Either validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) { + String iconUpdated = updatedComponent.getIcon(); + String iconCurrent = currentComponent.getIcon(); + if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either validatIconResponse = validateIcon(user, updatedComponent, null); + if (validatIconResponse.isRight()) { + ResponseFormat errorRespons = validatIconResponse.right().value(); + return Either.right(errorRespons); + } + currentComponent.setIcon(updatedComponent.getIcon()); + } else { + log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase()); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + protected Either, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) { + + log.trace("start deleteMarkedComponents"); + Either, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType); + + titanDao.commit(); + if ( deleteMarkedElements.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType)); + return Either.right(responseFormat); + } + log.trace("end deleteMarkedComponents"); + return Either.left(deleteMarkedElements.left().value()); + } + + public Either, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) { + List artifacts = new ArrayList<>(); + Either, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId); + if (artifactsResponse.isRight()) { + if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("failed to retrieve artifacts for {} {}", parentType, parentId); + return Either.right(artifactsResponse.right().value()); + } + } else { + artifacts.addAll(artifactsResponse.left().value().values()); + } + return Either.left(artifacts); + } + + /** + * + * @param componentId + * @param user + * @param dataParamsToReturn - ui list of params to return + * @return + */ + + public Either getComponentDataFilteredByParams(String componentId, User user, List dataParamsToReturn) { + + if (user != null) { + Either eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + } + + UiComponentDataTransfer result = new UiComponentDataTransfer(); + + if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) { + Either.left(result); + + } else { + Either uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn); + if(uiDataTransferEither.isRight()){ + return Either.right(uiDataTransferEither.right().value()); + } + result = uiDataTransferEither.left().value(); + } + + return Either.left(result); + } + + protected void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) { + List genericAndComponentInputs = new ArrayList<>(); + List genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType); + genericAndComponentInputs.addAll(genericInputs); + if (null != component.getInputs()){ + List nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs()); + genericAndComponentInputs.addAll(nonGenericInputsFromComponent); + } + component.setInputs(genericAndComponentInputs); + } + + private List getAllNonGenericInputsFromComponent(List genericInputs, List componentInputs) { + if (genericInputs == null) { + return componentInputs; + } + + Map inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName); + List componentNonGenericInputs = new ArrayList<>(); + componentInputs.stream().forEach(input -> { + if (!inputByNameMap.containsKey(input.getName())) { + componentNonGenericInputs.add(input); + } + }); + return componentNonGenericInputs; + } + + protected Either fetchAndSetDerivedFromGenericType(T component){ + Either genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component); + if(genericTypeEither.isRight()){ + log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType())); + } + Resource genericTypeResource = genericTypeEither.left().value(); + component.setDerivedFromGenericInfo(genericTypeResource); + return Either.left(genericTypeResource); + } + + public Either>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map> filters, String userId) { + Either>, ResponseFormat> response = null; + Either getResourceRes = null; + try{ + if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){ + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (userId != null && response == null) { + Either validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false); + if (validateUserRes.isRight()) { + response = Either.right(validateUserRes.right().value()); + } + } + if(response == null){ + getResourceRes = toscaOperationFacade.getToscaElement(componentId); + if(getResourceRes.isRight()){ + response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()))); + } + } + if(response == null){ + response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters); + } + } catch(Exception e){ + log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId); + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally{ + if (response.isLeft()){ + toscaOperationFacade.commit(); + } else { + toscaOperationFacade.rollback(); + } + } + return response; + } + + private Either>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map> filters) { + + Map> filteredProperties = new HashMap<>(); + Either>, ResponseFormat> result = Either.left(filteredProperties); + List filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE)); + String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0); + boolean searchByFragment = propertyNameFragment.length() > 3 ; + if(CollectionUtils.isNotEmpty(filteredInstances)){ + for(ComponentInstance instance : filteredInstances){ + if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){ + List currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currProperties)){ + filteredProperties.put(instance.getUniqueId(), currProperties); + } + } + if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){ + List currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment); + if(CollectionUtils.isNotEmpty(currInputs)){ + if(filteredProperties.get(instance.getUniqueId())!=null){ + filteredProperties.get(instance.getUniqueId()).addAll(currInputs); + } else { + filteredProperties.put(instance.getUniqueId(), currInputs); + } + } + } + } + } + return result; + } + + private List getFilteredComponentInstanceInputs(List inputs, String propertyNameFragment, boolean searchByFragment) { + return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private List getFilteredComponentInstanceProperties(List instanceProperties, String propertyNameFragment, boolean searchByFragment) { + return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList()); + } + + private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + return isMatching; + } + + private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) { + boolean isMatching = false; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){ + isMatching = true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + isMatching = true; + } + if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){ + isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment); + } + return isMatching; + } + + private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) { + String propertyType; + List dataTypeProperties; + DataTypeDefinition currentProperty; + if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){ + return true; + } + if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){ + return true; + } + + propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType(); + + if(ToscaPropertyType.isScalarType(propertyType)){ + return false; + } + Either getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType); + if(getDataTypeByNameRes.isRight()){ + return false; + } + currentProperty = getDataTypeByNameRes.left().value(); + dataTypeProperties = currentProperty.getProperties(); + + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + dataTypeProperties = currentProperty.getDerivedFrom().getProperties(); + if(CollectionUtils.isNotEmpty(dataTypeProperties)){ + for(PropertyDefinition prop : dataTypeProperties){ + if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){ + return true; + } + } + } + return false; + } + + private boolean isEmptyInnerType(PropertyDataDefinition property) { + return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null; + } + + public Either shouldUpgradeToLatestGeneric(Component clonedComponent) { + + if(!clonedComponent.deriveFromGeneric()) + return Either.left(false); + Boolean shouldUpgrade = false; + String currentGenericType = clonedComponent.getDerivedFromGenericType(); + String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion(); + Either fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent); + if(fetchAndSetLatestGeneric.isRight()) + return Either.right(fetchAndSetLatestGeneric.right().value()); + Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); + if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ + shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); + if(!shouldUpgrade) { + reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); + } + } + return Either.left(shouldUpgrade); + } + + private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) { + clonedComponent.setDerivedFromGenericType(currentGenericType); + clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); + } + + private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { + Map currentMap = ToscaDataDefinition.listToMapByName(currentList); + Map upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); + return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); + } + + private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ + + List genericTypeProps = latestGeneric.getProperties(); + Either, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + if (validMerge.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + List genericTypeAttributes = latestGeneric.getAttributes(); + validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); + if (validMerge.isRight()) { + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + return true; + } + private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) { - - if (!componentToCheckOut.shouldGenerateInputs()) { - //node type - validate properties and attributes - return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); - } - List genericTypeProps = latestGeneric.getProperties(); - List genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); - List currentList = new ArrayList<>(); - // nullify existing ownerId from existing list and merge into updated list - if (null != componentToCheckOut.getInputs()) { - for(InputDefinition input : componentToCheckOut.getInputs()) { - InputDefinition copy = new InputDefinition(input); - copy.setOwnerId(null); - currentList.add(copy); - } - } - if (null == genericTypeInputs) { - componentToCheckOut.setInputs(currentList); - return true; - } - - Either, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); - if (eitherMerged.isRight()) { - log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); - return false; - } - componentToCheckOut.setInputs(new ArrayList(eitherMerged.left().value().values())); - return true; - } - - - private List getFilteredInstances(Component component, List resourceTypes) { - List filteredInstances = null; - if(CollectionUtils.isEmpty(resourceTypes)){ - filteredInstances = component.getComponentInstances(); - } - else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ - filteredInstances = component.getComponentInstances() - .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); - } - if(filteredInstances == null){ - filteredInstances = new ArrayList<>(); - } - return filteredInstances; - } - - private boolean isMatchingType(OriginTypeEnum originType, List resourceTypes) { - boolean isMatchingType = false; - for(String resourceType : resourceTypes){ - if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ - isMatchingType = true; - break; - } - } - return isMatchingType; - } - - protected String cleanUpText(String text){ - text = ValidationUtils.removeNoneUtf8Chars(text); - text = ValidationUtils.normaliseWhitespace(text); - text = ValidationUtils.stripOctets(text); - text = ValidationUtils.removeHtmlTagsOnly(text); - return text; - } - - public Either shouldUpgradeToLatestDerived(Component clonedComponent) { - //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override - return Either.right(ActionStatus.GENERAL_ERROR); - } + + if (!componentToCheckOut.shouldGenerateInputs()) { + //node type - validate properties and attributes + return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); + } + List genericTypeProps = latestGeneric.getProperties(); + List genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); + List currentList = new ArrayList<>(); + // nullify existing ownerId from existing list and merge into updated list + if (null != componentToCheckOut.getInputs()) { + for(InputDefinition input : componentToCheckOut.getInputs()) { + InputDefinition copy = new InputDefinition(input); + copy.setOwnerId(null); + currentList.add(copy); + } + } + if (null == genericTypeInputs) { + componentToCheckOut.setInputs(currentList); + return true; + } + + Either, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); + if (eitherMerged.isRight()) { + log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); + return false; + } + componentToCheckOut.setInputs(new ArrayList(eitherMerged.left().value().values())); + return true; + } + + + private List getFilteredInstances(Component component, List resourceTypes) { + List filteredInstances = null; + if(CollectionUtils.isEmpty(resourceTypes)){ + filteredInstances = component.getComponentInstances(); + } + else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + filteredInstances = component.getComponentInstances() + .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList()); + } + if(filteredInstances == null){ + filteredInstances = new ArrayList<>(); + } + return filteredInstances; + } + + private boolean isMatchingType(OriginTypeEnum originType, List resourceTypes) { + boolean isMatchingType = false; + for(String resourceType : resourceTypes){ + if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){ + isMatchingType = true; + break; + } + } + return isMatchingType; + } + + protected String cleanUpText(String text){ + text = ValidationUtils.removeNoneUtf8Chars(text); + text = ValidationUtils.normaliseWhitespace(text); + text = ValidationUtils.stripOctets(text); + text = ValidationUtils.removeHtmlTagsOnly(text); + return text; + } + + public Either shouldUpgradeToLatestDerived(Component clonedComponent) { + //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override + return Either.right(ActionStatus.GENERAL_ERROR); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index b86b28a6c5..2eca73c560 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -20,25 +20,16 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.google.common.collect.Sets; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.version.PostChangeVersionOperationOrchestrator; import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic; import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -46,6 +37,8 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; @@ -53,25 +46,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; @@ -92,286 +70,369 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; -public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { - - private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName()); - - @Autowired - private IComponentInstanceOperation componentInstanceOperation; - - @Autowired - private ArtifactsBusinessLogic artifactBusinessLogic; - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; - - public static final String VF_MODULE = "org.openecomp.groups.VfModule"; - - public ComponentInstanceBusinessLogic() { - } - - public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { - return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); - } - - public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { - - Component origComponent = null; - Either resultOp = null; - User user = null; - org.openecomp.sdc.be.model.Component containerComponent = null; - ComponentTypeEnum containerComponentType; - - try { - Either resp = validateUserExists(userId, "create Component Instance", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } else { - user = resp.left().value(); - } - - Either validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); - if (validateValidJson.isRight()) { - return Either.right(validateValidJson.right().value()); - } - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } else { - containerComponentType = validateComponentType.left().value(); - } - - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } else { - containerComponent = validateComponentExists.left().value(); - } - - if (ModelConverter.isAtomicComponent(containerComponent)) { - log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); - } - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - if (resourceInstance != null && containerComponentType != null) { - OriginTypeEnum originType = resourceInstance.getOriginType(); - if (originType == OriginTypeEnum.ServiceProxy) { - Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); - } - origComponent = serviceProxyOrigin.left().value(); - - StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } - - } else { - Either getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); - - if (getOriginComponentRes.isRight()) { - return Either.right(getOriginComponentRes.right().value()); - } else { - origComponent = getOriginComponentRes.left().value(); - } - } - } - if (needLock) { - Either lockComponent = lockComponent(containerComponent, "createComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - log.debug("Try to create entry on graph"); - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { - resourceInstance.setIsProxy(true); - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreCapabiltyProperties(false); - filter.setIgnoreComponentInstances(false); - filter.setIgnoreRequirements(false); - Either serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); - if (serviceRes.isRight()) { - return serviceRes.right().value(); - } - Component service = serviceRes.left().value(); - Map> capabilities = service.getCapabilities(); - resourceInstance.setCapabilities(capabilities); - Map> req = service.getRequirements(); - resourceInstance.setRequirements(req); - - String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; - String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); - int lastIndexOf = toscaResourceName.lastIndexOf('.'); - if (lastIndexOf != -1) { - String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name; - resourceInstance.setToscaComponentName(proxyToscaName); - } - resourceInstance.setName(name); - resourceInstance.setIsProxy(true); - resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); - resourceInstance.setSourceModelName(service.getName()); - resourceInstance.setSourceModelUuid(service.getUUID()); - resourceInstance.setSourceModelUid(service.getUniqueId()); - resourceInstance.setComponentUid(proxyTemplate.getUniqueId()); - resourceInstance.setDescription("A Proxy for Service " + service.getName()); - resourceInstance.setComponentVersion(service.getVersion()); - - return StorageOperationStatus.OK; - } - - public Either createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { - - Either resultOp = null; - ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); - RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); - - Either resp = validateUserExists(userId, "create And Associate RI To RI", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - User user = resp.left().value(); - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - if (ModelConverter.isAtomicComponent(containerComponent)) { - log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); - } - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - - try { - log.debug("Try to create entry on graph"); - Either eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance, true); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component origComponent = eitherResourceName.left().value(); - - Either result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); - if (result.isRight()) { - log.debug("Failed to create resource instance {}", containerComponentId); - resultOp = Either.right(result.right().value()); - return resultOp; - - } - - log.debug("Entity on graph is created."); - ComponentInstance resResourceInfo = result.left().value(); - if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { - associationInfo.setFromNode(resResourceInfo.getUniqueId()); - } else { - associationInfo.setToNode(resResourceInfo.getUniqueId()); - } - - RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo); - Either resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); - if (resultReqCapDef.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); - CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef); - resultOp = Either.left(resInfo); - return resultOp; - - } else { - log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null)); - return resultOp; - } - - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - private Either getOriginComponentFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) { - Either eitherResponse; - Either eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); - if (eitherComponent.isRight()) { - log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName()); - eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); - } else { - eitherResponse = Either.left(eitherComponent.left().value()); - } - return eitherResponse; - } - - private Either createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { - Either resultOp; - - Either, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); - - if (result.isRight()) { - log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); - return resultOp; - } - - log.debug("Entity on graph is created."); - Component updatedComponent = result.left().value().getLeft(); - Map existingEnvVersions = new HashMap<>(); - // TODO existingEnvVersions ?? - Either addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); - if (addComponentInstanceArtifacts.isRight()) { - log.debug("Failed to create component instance {}", componentInstance.getName()); - resultOp = Either.right(addComponentInstanceArtifacts.right().value()); - return resultOp; - } - - Optional updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); - if (!updatedInstanceOptional.isPresent()) { - log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - return resultOp; - } - resultOp = Either.left(updatedInstanceOptional.get()); - return resultOp; - } +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + +@org.springframework.stereotype.Component +public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class); + + @Autowired + private IComponentInstanceOperation componentInstanceOperation; + + @Autowired + private ArtifactsBusinessLogic artifactBusinessLogic; + + @Autowired + private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; + + @Autowired + private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator; + + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; + + public ComponentInstanceBusinessLogic() { + } + + public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { + return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); + } + + public List getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List resList = new ArrayList<>(); + Map> ciPropertiesMap = component.getComponentInstancesProperties(); + if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){ + ciPropertiesMap.forEach(new BiConsumer>() { + @Override + public void accept(String s, List ciPropList) { + String ciName = ""; + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceProperty prop: ciPropList){ + List inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + public List getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + List resList = new ArrayList<>(); + Map> ciInputsMap = component.getComponentInstancesInputs(); + if(ciInputsMap != null && !ciInputsMap.isEmpty()){ + ciInputsMap.forEach(new BiConsumer>() { + @Override + public void accept(String s, List ciPropList) { + String ciName = ""; + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); + if(ciOp.isPresent()) + ciName = ciOp.get().getName(); + if (ciPropList != null && !ciPropList.isEmpty()) { + for(ComponentInstanceInput prop: ciPropList){ + List inputsValues = prop.getGetInputValues(); + if(inputsValues != null && !inputsValues.isEmpty()){ + for(GetInputValueDataDefinition inputData: inputsValues){ + if(isGetInputValueForInput(inputData, inputId)){ + prop.setComponentInstanceId(s); + prop.setComponentInstanceName(ciName); + resList.add(prop); + break; + } + } + } + + } + } + } + }); + } + return resList; + + } + + public Either createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) { + + Component origComponent = null; + Either resultOp = null; + User user = null; + org.openecomp.sdc.be.model.Component containerComponent = null; + ComponentTypeEnum containerComponentType; + + try { + Either resp = validateUserExists(userId, "create Component Instance", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } else { + user = resp.left().value(); + } + + Either validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class); + if (validateValidJson.isRight()) { + return Either.right(validateValidJson.right().value()); + } + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } else { + containerComponentType = validateComponentType.left().value(); + } + + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } else { + containerComponent = validateComponentExists.left().value(); + } + + if (ModelConverter.isAtomicComponent(containerComponent)) { + log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); + } + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + if (resourceInstance != null && containerComponentType != null) { + OriginTypeEnum originType = resourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); + + StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent); + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); + + } + + } else { + Either getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance); + + if (getOriginComponentRes.isRight()) { + return Either.right(getOriginComponentRes.right().value()); + } else { + origComponent = getOriginComponentRes.left().value(); + } + } + } + if (needLock) { + Either lockComponent = lockComponent(containerComponent, "createComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + log.debug("Try to create entry on graph"); + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) { + resourceInstance.setIsProxy(true); + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreRequirements(false); + Either serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); + if (serviceRes.isRight()) { + return serviceRes.right().value(); + } + Component service = serviceRes.left().value(); + Map> capabilities = service.getCapabilities(); + resourceInstance.setCapabilities(capabilities); + Map> req = service.getRequirements(); + resourceInstance.setRequirements(req); + + String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX; + String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName(); + int lastIndexOf = toscaResourceName.lastIndexOf('.'); + if (lastIndexOf != -1) { + String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name; + resourceInstance.setToscaComponentName(proxyToscaName); + } + resourceInstance.setName(name); + resourceInstance.setIsProxy(true); + resourceInstance.setSourceModelInvariant(service.getInvariantUUID()); + resourceInstance.setSourceModelName(service.getName()); + resourceInstance.setSourceModelUuid(service.getUUID()); + resourceInstance.setSourceModelUid(service.getUniqueId()); + resourceInstance.setComponentUid(proxyTemplate.getUniqueId()); + resourceInstance.setDescription("A Proxy for Service " + service.getName()); + resourceInstance.setComponentVersion(service.getVersion()); + + return StorageOperationStatus.OK; + } + + public Either createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) { + + Either resultOp = null; + ComponentInstance resourceInstance = createAndAssotiateInfo.getNode(); + RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate(); + + Either resp = validateUserExists(userId, "create And Associate RI To RI", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + User user = resp.left().value(); + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + if (ModelConverter.isAtomicComponent(containerComponent)) { + log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType())); + } + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + + try { + log.debug("Try to create entry on graph"); + Either eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component origComponent = eitherResourceName.left().value(); + + Either result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user); + if (result.isRight()) { + log.debug("Failed to create resource instance {}", containerComponentId); + resultOp = Either.right(result.right().value()); + return resultOp; + + } + + log.debug("Entity on graph is created."); + ComponentInstance resResourceInfo = result.left().value(); + if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) { + associationInfo.setFromNode(resResourceInfo.getUniqueId()); + } else { + associationInfo.setToNode(resResourceInfo.getUniqueId()); + } + + RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo; + Either resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef); + if (resultReqCapDef.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value(); + CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef); + resultOp = Either.left(resInfo); + return resultOp; + + } else { + log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null)); + return resultOp; + } + + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + private Either getOriginComponentFromComponentInstance(ComponentInstance componentInstance) { + return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid()); + } + + private Either getInstanceOriginNode(ComponentInstance componentInstance) { + return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid()); + } + + private Either getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) { + Either eitherResponse; + Either eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId); + if (eitherComponent.isRight()) { + log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName); + eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null)); + } else { + eitherResponse = Either.left(eitherComponent.left().value()); + } + return eitherResponse; + } + + private Either createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) { + Either resultOp; + + Either, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user); + + if (result.isRight()) { + log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null)); + return resultOp; + } + + log.debug("Entity on graph is created."); + Component updatedComponent = result.left().value().getLeft(); + Map existingEnvVersions = new HashMap<>(); + // TODO existingEnvVersions ?? + Either addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions); + if (addComponentInstanceArtifacts.isRight()) { + log.debug("Failed to create component instance {}", componentInstance.getName()); + resultOp = Either.right(addComponentInstanceArtifacts.right().value()); + return resultOp; + } + + Optional updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst(); + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + return resultOp; + } + resultOp = Either.left(updatedInstanceOptional.get()); + return resultOp; + } /** * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts @@ -382,2012 +443,2196 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param existingEnvVersions * @return */ - protected Either addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map existingEnvVersions) { - - log.debug("add artifacts to resource instance"); - List filteredGroups = null; - ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); - if (!ActionStatus.OK.equals(status)) { - ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); - return Either.right(resultOp); - } - StorageOperationStatus artStatus; - // generate heat_env if necessary - Map componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { - - Map finalDeploymentArtifacts = new HashMap(); - Map> groupInstancesArtifacts = new HashMap<>(); - - for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { - String type = artifact.getArtifactType(); - if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { - finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - } - if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { - continue; - } - if (artifact.checkEsIdExist()) { - Either createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, - componentInstance.getName(), user, containerComponent, existingEnvVersions); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); - // put env - finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - if (CollectionUtils.isNotEmpty(originComponent.getGroups())) { - filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); - } - if (CollectionUtils.isNotEmpty(filteredGroups)) { - for (GroupDefinition groupInstance : filteredGroups) { - Optional op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); - if (op.isPresent()) { - List artifactsUid; - if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { - artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); - } else { - artifactsUid = new ArrayList<>(); - } - artifactsUid.add(artifactDefinition); - groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); - break; - } - } - } - } - } - artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); - if (artStatus != StorageOperationStatus.OK) { - log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - - } - StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); - if (result != StorageOperationStatus.OK) { - log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); - } - componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); - } - - artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); - if (artStatus != StorageOperationStatus.OK) { - log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); - - } - componentInstance.setArtifacts(originComponent.getArtifacts()); - return Either.left(ActionStatus.OK); - } - - private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { - Either, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null); - - Map deploymentArtifacts = new HashMap(); - if (getResourceDeploymentArtifacts.isRight()) { - StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); - if (!status.equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); - return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); - } - } else { - deploymentArtifacts = getResourceDeploymentArtifacts.left().value(); - } - - if (!deploymentArtifacts.isEmpty()) { - Map tempDeploymentArtifacts = new HashMap(deploymentArtifacts); - for (Entry artifact : deploymentArtifacts.entrySet()) { - if (!artifact.getValue().checkEsIdExist()) { - tempDeploymentArtifacts.remove(artifact.getKey()); - } - } - - resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts); - } - - return ActionStatus.OK; - } - - public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { - return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); - } - - public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, - boolean needLock, boolean createNewTransaction) { - - Either resp = validateUserExists(userId, "update Component Instance", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either resultOp = null; - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - ComponentTypeEnum instanceType = getComponentType(containerComponentType); - Either validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); - if (validateParentStatus.isRight()) { - log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); - return resultOp; - } - if (!validateParentStatus.left().value()) { - resultOp = Either.right( - componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); - return resultOp; - } - - if (needLock) { - Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - try { - - Either eitherResourceName = getOriginComponentFromComponentInstance(componentInstance, inTransaction); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - Component origComponent = eitherResourceName.left().value(); - - resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - // New Multiple Instance Update API - public Either, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List componentInstanceList, boolean needLock, - boolean createNewTransaction) { - - Either, ResponseFormat> resultOp = null; - org.openecomp.sdc.be.model.Component containerComponent = null; - try { - Either resp = validateUserExists(userId, "update Component Instance", true); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - ComponentParametersView componentFilter = new ComponentParametersView(); - componentFilter.disableAll(); - componentFilter.setIgnoreUsers(false); - componentFilter.setIgnoreComponentInstances(false); - Either validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - - containerComponent = validateComponentExists.left().value(); - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - ComponentTypeEnum instanceType = getComponentType(containerComponentType); - - for (ComponentInstance componentInstance : componentInstanceList) { - boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); - if (!validateParent) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), - containerComponentId)); - return resultOp; - } - } - - if (needLock) { - - Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedList = new ArrayList<>(); - List instancesFromContainerComponent = containerComponent.getComponentInstances(); - List listForUpdate = new ArrayList<>(); - if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) - containerComponent.setComponentInstances(componentInstanceList); - else { - Iterator iterator = instancesFromContainerComponent.iterator(); - while (iterator.hasNext()) { - ComponentInstance origInst = iterator.next(); - Optional op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); - if (op.isPresent()) { - ComponentInstance updatedCi = op.get(); - updatedCi = buildComponentInstance(updatedCi, origInst); - - Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); - if (!isUniqueName) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); - return resultOp; - } - - listForUpdate.add(updatedCi); - } else - listForUpdate.add(origInst); - } - containerComponent.setComponentInstances(listForUpdate); - - if (resultOp == null) { - Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); - if (updateStatus.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); - return resultOp; - } - for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { - Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); - if (op.isPresent()) { - updatedList.add(updatedInstance); - } - } - } - } - - resultOp = Either.left(updatedList); - return resultOp; - - } finally { - if (needLock) { - unlockComponent(resultOp, containerComponent); - } - } - } - - private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) { - return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId)); - } - - private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { - if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { - return ComponentTypeEnum.SERVICE_INSTANCE; - } else { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } - } - - private Either updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, - ComponentInstance componentInstance) { - - Either resultOp = null; - Optional componentInstanceOptional = null; - Either, StorageOperationStatus> updateRes = null; - ComponentInstance oldComponentInstance = null; - boolean isNameChanged = false; - - if (resultOp == null) { - componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); - if (!componentInstanceOptional.isPresent()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } - } - if (resultOp == null) { - oldComponentInstance = componentInstanceOptional.get(); - String newInstanceName = componentInstance.getName(); - if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) - isNameChanged = true; - Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); - if (!isUniqueName) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); - } - } - if (resultOp == null) { - updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); - if (updateRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), - updateRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); - } else { - // region - Update instance Groups - if (isNameChanged) { - Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); - if (result.isRight()) - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); - } - // endregion - } - } - if (resultOp == null) { - String newInstanceId = updateRes.left().value().getRight(); - Optional updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); - - if (!updatedInstanceOptional.isPresent()) { - log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); - } else { - resultOp = Either.left(updatedInstanceOptional.get()); - } - - } - if (resultOp == null) { - resultOp = Either.left(componentInstanceOptional.get()); - } - return resultOp; - } - - /** - * @param oldPrefix- - * The normalized old vf name - * @param newNormailzedPrefix- - * The normalized new vf name - * @param qualifiedGroupInstanceName- - * old Group Instance Name - **/ - // modify group names - private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) { - if (qualifiedGroupInstanceName == null) { - log.info("CANNOT change group name "); - return null; - } - if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) - return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix); - return qualifiedGroupInstanceName; - } - - private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) { - oldComponentInstance.setName(newComponentInstance.getName()); - oldComponentInstance.setModificationTime(System.currentTimeMillis()); - oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); - if (oldComponentInstance.getGroupInstances() != null) - oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); - return oldComponentInstance; - } - - public Either deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { - - Either resp = validateUserExists(userId, "delete Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either lockComponent = lockComponent(containerComponent, "deleteComponentInstance"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - // validate resource - /* - * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils - * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) { - * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } - */ - Either resultOp = null; - try { - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - return resultOp; - - } finally { - /* - * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service); - */ - unlockComponent(resultOp, containerComponent); - } - } - - private Either deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { - - Either resultOp = null; - ComponentInstance deletedInstance = null; - Either, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); - - if (deleteRes.isRight()) { - log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } - if (resultOp == null) { - log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); - deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); - resultOp = Either.left(deletedInstance); - } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { - List groupsToUpdate = new ArrayList<>(); - for (GroupDataDefinition currGroup : containerComponent.getGroups()) { - Map members = currGroup.getMembers(); - if (members != null && members.containsKey(deletedInstance.getName())) { - members.remove(deletedInstance.getName()); - groupsToUpdate.add(currGroup); - } - } - Either, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate); - if (updateGroupsRes.isRight()) { - log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); - ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); - resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); - } - } - if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { - List inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); - if (CollectionUtils.isNotEmpty(inputsToDelete)) { - StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); - if (deleteInputsRes != StorageOperationStatus.OK) { - log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); - } - } - } - return resultOp; - } - - private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { - ComponentInstance foundInstance = null; - for (ComponentInstance instance : containerComponent.getComponentInstances()) { - if (instance.getUniqueId().equals(componentInstanceId)) { - foundInstance = instance; - containerComponent.getComponentInstances().remove(instance); - break; - } - } - return foundInstance; - } - - public Either associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true); - } - - public Either associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock, - boolean createNewTransaction) { - - Either resp = validateUserExists(userId, "associate Ri To RI", inTransaction); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either resultOp = null; - - Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - if (needLock) { - Either lockComponent = lockComponent(containerComponent, "associateRIToRI"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - try { - - resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); - - return resultOp; - - } finally { - if (needLock) - unlockComponent(resultOp, containerComponent); - } - } - - public Either associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { - - log.debug("Try to create entry on graph"); - Either resultOp = null; - - Either result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); - - if (result.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; - - } else { - log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); - String fromNameOrId = ""; - String toNameOrId = ""; - Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); - Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - - toNameOrId = requirementDef.getFromNode(); - fromNameOrId = requirementDef.getFromNode(); - if (fromResult.isLeft()) { - fromNameOrId = fromResult.left().value().getName(); - } - if (toResult.isLeft()) { - toNameOrId = toResult.left().value().getName(); - } - - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - - return resultOp; - } - - } - - public Either dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { - Either resp = validateUserExists(userId, "dissociate RI From RI", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either resultOp = null; - Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - Either lockComponent = lockComponent(containerComponent, "associateRIToRI"); - - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - try { - log.debug("Try to create entry on graph"); - Either result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); - if (result.isLeft()) { - log.debug("Enty on graph is created."); - RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); - resultOp = Either.left(requirementCapabilityRelDef); - return resultOp; - - } else { - - log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); - String fromNameOrId = ""; - String toNameOrId = ""; - Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); - Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); - - toNameOrId = requirementDef.getFromNode(); - fromNameOrId = requirementDef.getFromNode(); - if (fromResult.isLeft()) { - fromNameOrId = fromResult.left().value().getName(); - } - if (toResult.isLeft()) { - toNameOrId = toResult.left().value().getName(); - } - - resultOp = Either - .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); - return resultOp; - } - } finally { - unlockComponent(resultOp, containerComponent); - } - } - /** - * Allows to get relation contained in specified component according to received Id - * @param componentId - * @param relationId - * @param userId - * @param componentTypeEnum - * @return - */ - public Either getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) { - - Either resultOp = null; - try { - org.openecomp.sdc.be.model.Component containerComponent = null; - Either validateComponentExists = null; - RequirementCapabilityRelDef foundRelation = null; - - Either validateUserRes = validateUserExists(userId, "get relation by Id", false); - if (validateUserRes.isRight()) { - resultOp = Either.right(validateUserRes.right().value()); - } - if(resultOp == null){ - validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); - if (validateComponentExists.isRight()) { - resultOp = Either.right(validateComponentExists.right().value()); - } - } - if(resultOp == null){ - containerComponent = validateComponentExists.left().value(); - List requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); - foundRelation = findRelation(relationId, requirementCapabilityRelations); - if(foundRelation == null){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); - log.debug("Relation with id {} was not found on the component", relationId, componentId); - resultOp = Either.right(responseFormat); - } - } - if(resultOp == null){ - resultOp = setRelatedCapability(foundRelation, containerComponent); - } - if(resultOp.isLeft()){ - resultOp = setRelatedRequirement(foundRelation, containerComponent); - } - } catch (Exception e) { - log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return resultOp; - } - - private RequirementCapabilityRelDef findRelation(String relationId, List requirementCapabilityRelations) { - for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ - if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){ - return relationship; - } - } - return null; - } - - private Either setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { - Either result = null; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); - String instanceId = foundRelation.getFromNode(); - Optional foundRequirement; - Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instance.isPresent()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); - log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } - if(result == null){ - for(List requirements : instance.get().getRequirements().values()){ - foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); - if(foundRequirement.isPresent()){ - foundRelation.getSingleRelationship().setRequirement(foundRequirement.get()); - result = Either.left(foundRelation); - } - } - } - if(result == null){ - Either getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); - if(getfulfilledRequirementRes.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); - log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } else { - foundRelation.getSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value()); - } - } - if(result == null){ - result = Either.left(foundRelation); - } - return result; - } - - private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { - return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) && - req.getName().equals(relationshipInfo.getRequirement()) && - req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && - req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); - } - - private Either setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { - Either result = null; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); - String instanceId = foundRelation.getToNode(); - Optional foundCapability; - Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instance.isPresent()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); - log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } - if(result == null){ - for(List capabilities : instance.get().getCapabilities().values()){ - foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); - if(foundCapability.isPresent()){ - foundRelation.getSingleRelationship().setCapability(foundCapability.get()); - result = Either.left(foundRelation); - } - } - } - if(result == null){ - Either getfulfilledRequirementRes = - toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); - if(getfulfilledRequirementRes.isRight()){ - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); - result = Either.right(responseFormat); - } else { - foundRelation.getSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); - } - } - if(result == null){ - result = Either.left(foundRelation); - } - return result; - } - - private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { - return cap.getName().equals(relationshipInfo.getCapability()) && - cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && - cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); - } - - private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); - Either result; - if (eitherAttribute.isLeft()) { - log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); - ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); - - result = Either.left(instanceAttribute); - - } else { - log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); - - result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); - - } - return result; - } - - private Either createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - - Either result; - - Wrapper indexCounterWrapper = new Wrapper<>(); - Wrapper errorWrapper = new Wrapper<>(); - validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper); - - if (!errorWrapper.isEmpty()) { - result = Either.right(errorWrapper.getInnerElement()); - } else { - Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); - if (eitherAttribute.isLeft()) { - log.debug("Attribute value was added to resource instance {}", resourceInstanceId); - ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); - result = Either.left(instanceAttribute); - - } else { - log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); - result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - } - } - return result; - } - - /** - * Create Or Updates Attribute Instance - * - * @param componentTypeEnum - * @param componentId - * @param resourceInstanceId - * @param attribute - * @param userId - * @return - */ - public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { - Either result = null; - Wrapper errorWrapper = new Wrapper<>(); - - validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); - if (errorWrapper.isEmpty()) { - validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper); - } - if (errorWrapper.isEmpty()) { - validateComponentLock(componentId, componentTypeEnum, errorWrapper); - } - - try { - if (errorWrapper.isEmpty()) { - final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid()); - if (isCreate) { - result = createAttributeValue(attribute, resourceInstanceId); - } else { - result = updateAttributeValue(attribute, resourceInstanceId); - } - } else { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - } - - finally { - if (result == null || result.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - } - - private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { - return StringUtils.isNotEmpty(property.getValue()) - && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) - && ComponentTypeEnum.SERVICE == componentTypeEnum; - } - - private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) { - return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property)); - } - - // US833308 VLI in service - specific network_role property value logic - private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List properties) { - for (ComponentInstanceProperty property: properties) { - if (isNetworkRoleServiceProperty(property, componentTypeEnum)) { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreComponentInstances(false); - Either getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - if (getServiceResult.isRight()) { - return getServiceResult.right().value(); - } - Component service = getServiceResult.left().value(); - Optional getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); - if (!getInstance.isPresent()) { - return StorageOperationStatus.NOT_FOUND; - } - String prefix = service.getSystemName() + "."; - String value = property.getValue(); - if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { - property.setValue(prefix + value); - } - } - } - return StorageOperationStatus.OK; - } - - private Either updatePropertyObjectValue(ComponentInstanceProperty property, Map allDataTypes) { - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); - String newValue = property.getValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, true); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - return Either.left(newValue); - } - - public Either createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) { - - Either resultOp = null; - - Either resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on service {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; - } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // specific property value logic US833308 - StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property); - if (StorageOperationStatus.OK != fetchByIdsStatus) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); - - String newValue = property.getValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - - try { - List instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId); - Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - instanceProperty.get().setValue(newValue); - if (instanceProperty.isPresent()) { - status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); - } else { - status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); - } - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - List path = new ArrayList<>(); - path.add(foundResourceInstance.getUniqueId()); - property.setPath(path); - - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(property); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) { - - Either resultOp = null; - - Either resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on service {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); - return resultOp; - } - - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - String innerType = null; - String propertyType = property.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = property.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value()); - - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (!res) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } - - try { - List instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId); - Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - if (instanceProperty.isPresent()) { - instanceProperty.get().setValue(property.getValue()); - status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); - } else { - status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property); - } - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(property); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, - String userId) { - - Either resultOp = null; - - Either resp = validateUserExists(userId, "create Or Update Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user: {} on service: {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - String propertyValueUid = property.getValueUniqueUid(); - - if (propertyValueUid == null) { - - Either counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Integer index = counterRes.left().value(); - Either result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); - - if (result.isLeft()) { - log.trace("Property value was added to resource instance {}", resourceInstanceId); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - - } else { - log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - } - - } else { - Either result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - - } else { - log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - } - } - if (resultOp.isLeft()) { - StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId); - if (updateCustomizationUUID != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - } - } - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) { - - Either resultOp = null; - - Either resp = validateUserExists(userId, "create Or Update Input Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user: {} on service: {}", userId, componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", componentId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - String propertyValueUid = inputProperty.getValueUniqueUid(); - if (propertyValueUid == null) { - - Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); - - if (counterRes.isRight()) { - log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Integer index = counterRes.left().value(); - Either result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true); - - if (result.isLeft()) { - log.debug("Property value was added to resource instance {}", resourceInstanceId); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - - } else { - Either result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid()); - ComponentInstanceInput instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - } - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); - } - - } - - public Either deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { - - Either resp = validateUserExists(userId, "delete Property Value", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either resultOp = null; - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - return resultOp; - } - - if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) { - log.info("Restricted operation for user {} on service {}", userId, serviceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return resultOp; - } - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock service {}", serviceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - return resultOp; - } - try { - Either result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); - - if (result.isLeft()) { - log.debug("Property value {} was removed from graph.", propertyValueId); - ComponentInstanceProperty instanceProperty = result.left().value(); - - resultOp = Either.left(instanceProperty); - return resultOp; - - } else { - log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId); - - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); - - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - - return resultOp; - } - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); - } - - } - - private Either getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { - - Either eitherResponse = null; - ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); - Component component; - ResponseFormat errorResponse; - Either getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); - if (getComponentRes.isRight()) { - log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); - errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - eitherResponse = Either.right(errorResponse); - } - if (eitherResponse == null) { - component = getComponentRes.left().value(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { - ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; - errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); - eitherResponse = Either.right(errorResponse); - } - } - if (eitherResponse == null) { - eitherResponse = Either.left(getComponentRes.left().value()); - } - return eitherResponse; - } - - public Either changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { - - Either resp = validateUserExists(userId, "change Component Instance Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - User user = resp.left().value(); - Either resultOp = null; - - Either validateComponentType = validateComponentType(containerComponentParam); - if (validateComponentType.isRight()) { - return Either.right(validateComponentType.right().value()); - } - - final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); - - Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); - if (validateComponentExists.isRight()) { - return Either.right(validateComponentExists.right().value()); - } - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); - - Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); - if (validateCanWorkOnComponent.isRight()) { - return Either.right(validateCanWorkOnComponent.right().value()); - } - - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); - return resultOp; - } - - ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); - - Either lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - - try { - - - if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { - resultOp = Either.left(currentResourceInstance); - return resultOp; - - } - String resourceId = newComponentInstance.getComponentUid(); - - - - Either componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); - if (componentExistsRes.isRight()) { - log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); - return resultOp; - } else if (!componentExistsRes.left().value()) { - log.debug("The resource {} not found ", resourceId); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return resultOp; - } - - Either eitherOriginComponent = getOriginComponentFromComponentInstance(currentResourceInstance, true); - - if (eitherOriginComponent.isRight()) { - resultOp = Either.right(eitherOriginComponent.right().value()); - return resultOp; - } - DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); - resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - if (resultOp.isRight()) { - log.debug("failed to delete resource instance {}", resourceId); - return resultOp; - } - ComponentInstance resResourceInfo = resultOp.left().value(); - Component origComponent = null; - OriginTypeEnum originType = currentResourceInstance.getOriginType(); - if (originType == OriginTypeEnum.ServiceProxy) { - Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); - } - origComponent = serviceProxyOrigin.left().value(); - - StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); - - if (fillProxyRes != StorageOperationStatus.OK) { - log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); - - } - newComponentInstance.setOriginType(originType); - }else{ - - - Either eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance, true); - - if (eitherResourceName.isRight()) { - resultOp = Either.right(eitherResourceName.right().value()); - return resultOp; - } - - origComponent = eitherResourceName.left().value(); - - newComponentInstance.setName(resResourceInfo.getName()); - //newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition) origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName()); - } - - newComponentInstance.setInvariantName(resResourceInfo.getInvariantName()); - newComponentInstance.setPosX(resResourceInfo.getPosX()); - newComponentInstance.setPosY(resResourceInfo.getPosY()); - newComponentInstance.setDescription(resResourceInfo.getDescription()); - - resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); - - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - - ComponentInstance updatedComponentInstance = resultOp.left().value(); - if (resultOp.isRight()) { - log.debug("failed to create resource instance {}", resourceId); - return resultOp; - } - - Either mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); - if (mergeStatusEither.isRight()) { - return Either.right(mergeStatusEither.right().value()); - } - - /* - * if (CollectionUtils.isNotEmpty(groupInstances)) { StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance( containerComponent, updatedComponentInstance, groupInstances); if - * (addGroupsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError( "ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); - * resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); return resultOp; } - * - * - * } if (MapUtils.isNotEmpty(deploymentArtifacts)) { StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance( containerComponent, updatedComponentInstance, - * deploymentArtifacts); if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError( "ChangeComponentInstanceVersion", - * "Failed to associate groups to new component instance", ErrorSeverity.ERROR); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); return resultOp; } } - */ - - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - Either updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); - if (updatedComponentRes.isRight()) { - StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("Component with id {} was not found", containerComponentId); - return Either.right(responseFormat); - } - resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); - return resultOp; - } - resultOp = Either.left(resourceInstanceStatus.left().value()); - return resultOp; - - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin(); - - protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance(); - - // US831698 - public Either, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { - final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; - Component containerComponent = null; - - Either, ResponseFormat> resultOp = null; - try { - Either validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); - if (validateUserExists.isRight()) { - resultOp = Either.right(validateUserExists.right().value()); - return resultOp; - } - - Either validateComponentType = validateComponentType(containerComponentTypeParam); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - return resultOp; - } - - Either validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); - if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - return resultOp; - } - containerComponent = validateContainerComponentExists.left().value(); - - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - return resultOp; - } - - List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); - if (CollectionUtils.isEmpty(instanceProperties)) { - instanceProperties = new ArrayList<>(); - } - resultOp = Either.left(instanceProperties); - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper instaceCounterWrapper, Wrapper errorWrapper) { - Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); - - if (counterRes.isRight()) { - log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId); - StorageOperationStatus status = counterRes.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus)); - } else { - instaceCounterWrapper.setInnerElement(counterRes.left().value()); - } - - } - - /** - * updates componentInstance modificationTime - * - * @param componentInstance - * @param componentInstanceType - * @param modificationTime - * @param inTransaction - * @return - */ - public Either updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { - Either result; - Either updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, - inTransaction); - if (updateComponentInstanceRes.isRight()) { - log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value()))); - } else { - result = Either.left(updateComponentInstanceRes.left().value()); - } - return result; - } - - public Either deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { - // TODO Add implementation - Either result = Either.left(new ComponentInstance()); - return result; - } - - public Either createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) { - // TODO Add implementation - Either result = Either.left(new ComponentInstance()); - return result; - } - - public Either changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { - // TODO Add implementation - Either result = Either.left(new ComponentInstance()); - return result; - } - - private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { - Boolean isUnique = true; - String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName); - if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) { - Optional foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst(); - if (foundComponentInstance.isPresent()) { - isUnique = false; - } - } - return isUnique; - } - - private Either getResourceInstanceById(Component containerComponent, String instanceId) { - - Either result = null; - List instances = containerComponent.getComponentInstances(); - Optional foundInstance = null; - if (CollectionUtils.isEmpty(instances)) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - if (result == null) { - foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if (!foundInstance.isPresent()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null) { - result = Either.left(foundInstance.get()); - } - return result; - } - - private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { - - Long creationDate = origInstanceForUpdate.getCreationTime(); - - Long modificationTime = System.currentTimeMillis(); - resourceInstanceForUpdate.setCreationTime(creationDate); - resourceInstanceForUpdate.setModificationTime(modificationTime); - - resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) { - resourceInstanceForUpdate.setName(origInstanceForUpdate.getName()); - } - - resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName())); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) - resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) - resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) - resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); - - if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) - resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); - - if (resourceInstanceForUpdate.getOriginType() == null) { - resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); - } - if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) - resourceInstanceForUpdate.setIsProxy(true); - if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { - resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); - } - if (resourceInstanceForUpdate.getSourceModelName() == null) { - resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName()); - } - if (resourceInstanceForUpdate.getSourceModelUuid() == null) { - resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid()); - } - if (resourceInstanceForUpdate.getSourceModelUid() == null) { - resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); - } - return resourceInstanceForUpdate; - } - /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type - * @param containerComponentType - * @param containerComponentId - * @param componentInstanceUniqueId - * @param capabilityType - * @param capabilityName - * @param userId - * @return - */ - public Either, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String userId) { - - Component containerComponent = null; - - Either, ResponseFormat> resultOp = null; - try { - Either validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false); - if (validateUserExists.isRight()) { - resultOp = Either.right(validateUserExists.right().value()); - } - if(resultOp == null){ - Either validateComponentType = validateComponentType(containerComponentType); - if (validateComponentType.isRight()) { - resultOp = Either.right(validateComponentType.right().value()); - } - } - if(resultOp == null){ - Either validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); - if (validateContainerComponentExists.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); - } else { - containerComponent = validateContainerComponentExists.left().value(); - } - } - if(resultOp == null){ - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } else { - resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, resourceInstanceStatus.left().value().getCapabilities()); - } - } - return resultOp; - } finally { - unlockComponent(resultOp, containerComponent); - } - } - - private Either, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, Map> instanceCapabilities) { - Either, ResponseFormat> result = null; - CapabilityDefinition foundCapability; - if (MapUtils.isNotEmpty(instanceCapabilities)) { - List capabilitiesPerType = instanceCapabilities.get(capabilityType); - if (capabilitiesPerType != null) { - Optional capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName)).findFirst(); - if (capabilityOpt.isPresent()) { - foundCapability = capabilityOpt.get(); - result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); - } - } - } - if (result == null) { - result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName); - } - return result; - } - - private Either, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName) { - Either, ResponseFormat> resultOp = null; - try { - Either, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType); - if(getComponentInstanceCapabilityProperties.isRight()){ - resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); - } else { - resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); - } - } catch(Exception e){ - log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); - resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return resultOp; - } - - private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, - String capabilityType, String capabilityName) { - String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); - StringBuilder sb = new StringBuilder(componentInstanceUniqueId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); - String capKey = sb.toString(); - - Map> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) - .orElse(Collections.emptyMap()); - List capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); - Optional cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny(); - if (cap.isPresent()) { - List capProperties = cap.get().getProperties(); - if (capProperties != null) { - Optional instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - if (instanceProperty.isPresent()) { - instanceProperty.get().setValue(newValue); - List path = new ArrayList<>(); - path.add(componentInstanceUniqueId); - path.add(capKey); - instanceProperty.get().setPath(path); - status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); - - } - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - } - } - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, - List properties, String userId) { - Either, ResponseFormat> resultOp = null; - - Either resp = validateUserExists(userId, "update instance capability property", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - Either getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve component, component id {}", containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock component {}", containerComponentId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - } - - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - } - - try { - for (ComponentInstanceProperty property : properties) { - Either newPropertyValueEither = updatePropertyObjectValue(property, allDataTypes.left().value()); - newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), - responseFormat -> Either.right(responseFormat)); - } - Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(properties); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); - } - } + protected Either addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map existingEnvVersions) { + + log.debug("add artifacts to resource instance"); + List filteredGroups = null; + ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance); + if (!ActionStatus.OK.equals(status)) { + ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null); + return Either.right(resultOp); + } + StorageOperationStatus artStatus; + // generate heat_env if necessary + Map componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts(); + if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) { + + Map finalDeploymentArtifacts = new HashMap(); + Map> groupInstancesArtifacts = new HashMap<>(); + + for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { + String type = artifact.getArtifactType(); + if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) { + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); + } + if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { + continue; + } + if (artifact.checkEsIdExist()) { + Either createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, + componentInstance.getName(), user, containerComponent, existingEnvVersions); + if (createHeatEnvPlaceHolder.isRight()) { + return Either.right(createHeatEnvPlaceHolder.right().value()); + } + ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); + // put env + finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + if (CollectionUtils.isNotEmpty(originComponent.getGroups())) { + filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); + } + if (CollectionUtils.isNotEmpty(filteredGroups)) { + for (GroupDefinition groupInstance : filteredGroups) { + Optional op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny(); + if (op.isPresent()) { + List artifactsUid; + if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) { + artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId()); + } else { + artifactsUid = new ArrayList<>(); + } + artifactsUid.add(artifactDefinition); + groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid); + break; + } + } + } + } + } + artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts); + if (artStatus != StorageOperationStatus.OK) { + log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + + } + StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts); + if (result != StorageOperationStatus.OK) { + log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result))); + } + componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts); + } + + artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts()); + if (artStatus != StorageOperationStatus.OK) { + log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false))); + + } + componentInstance.setArtifacts(originComponent.getArtifacts()); + return Either.left(ActionStatus.OK); + } + + private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) { + Either, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null); + + Map deploymentArtifacts = new HashMap(); + if (getResourceDeploymentArtifacts.isRight()) { + StorageOperationStatus status = getResourceDeploymentArtifacts.right().value(); + if (!status.equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status); + return componentsUtils.convertFromStorageResponseForResourceInstance(status, true); + } + } else { + deploymentArtifacts = getResourceDeploymentArtifacts.left().value(); + } + + if (!deploymentArtifacts.isEmpty()) { + Map tempDeploymentArtifacts = new HashMap(deploymentArtifacts); + for (Entry artifact : deploymentArtifacts.entrySet()) { + if (!artifact.getValue().checkEsIdExist()) { + tempDeploymentArtifacts.remove(artifact.getKey()); + } + } + + resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts); + } + + return ActionStatus.OK; + } + + public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) { + return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true); + } + + public Either updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, + boolean needLock, boolean createNewTransaction) { + + Either resp = validateUserExists(userId, "update Component Instance", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either resultOp = null; + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + ComponentTypeEnum instanceType = getComponentType(containerComponentType); + Either validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid()); + if (validateParentStatus.isRight()) { + log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase())); + return resultOp; + } + if (!validateParentStatus.left().value()) { + resultOp = Either.right( + componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId)); + return resultOp; + } + + if (needLock) { + Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + try { + + Either eitherResourceName = getOriginComponentFromComponentInstance(componentInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component origComponent = eitherResourceName.left().value(); + + resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance); + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + // New Multiple Instance Update API + public Either, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List componentInstanceList, boolean needLock, + boolean createNewTransaction) { + + Either, ResponseFormat> resultOp = null; + org.openecomp.sdc.be.model.Component containerComponent = null; + try { + Either resp = validateUserExists(userId, "update Component Instance", true); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + + ComponentParametersView componentFilter = new ComponentParametersView(); + componentFilter.disableAll(); + componentFilter.setIgnoreUsers(false); + componentFilter.setIgnoreComponentInstances(false); + Either validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + + containerComponent = validateComponentExists.left().value(); + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + ComponentTypeEnum instanceType = getComponentType(containerComponentType); + + for (ComponentInstance componentInstance : componentInstanceList) { + boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId()); + if (!validateParent) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), + containerComponentId)); + return resultOp; + } + } + + if (needLock) { + + Either lockComponent = lockComponent(containerComponent, "updateComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + + List updatedList = new ArrayList<>(); + List instancesFromContainerComponent = containerComponent.getComponentInstances(); + List listForUpdate = new ArrayList<>(); + if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) + containerComponent.setComponentInstances(componentInstanceList); + else { + Iterator iterator = instancesFromContainerComponent.iterator(); + while (iterator.hasNext()) { + ComponentInstance origInst = iterator.next(); + Optional op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny(); + if (op.isPresent()) { + ComponentInstance updatedCi = op.get(); + updatedCi = buildComponentInstance(updatedCi, origInst); + + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName()); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName())); + return resultOp; + } + + listForUpdate.add(updatedCi); + } else + listForUpdate.add(origInst); + } + containerComponent.setComponentInstances(listForUpdate); + + if (resultOp == null) { + Either updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter); + if (updateStatus.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null)); + return resultOp; + } + for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) { + Optional op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny(); + if (op.isPresent()) { + updatedList.add(updatedInstance); + } + } + } + } + + resultOp = Either.left(updatedList); + return resultOp; + + } finally { + if (needLock) { + unlockComponent(resultOp, containerComponent); + } + } + } + + private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) { + return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId)); + } + + private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) { + if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) { + return ComponentTypeEnum.SERVICE_INSTANCE; + } else { + return ComponentTypeEnum.RESOURCE_INSTANCE; + } + } + + private Either updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId, + ComponentInstance componentInstance) { + + Either resultOp = null; + Optional componentInstanceOptional = null; + Either, StorageOperationStatus> updateRes = null; + ComponentInstance oldComponentInstance = null; + boolean isNameChanged = false; + + if (resultOp == null) { + componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst(); + if (!componentInstanceOptional.isPresent()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + } + } + if (resultOp == null) { + oldComponentInstance = componentInstanceOptional.get(); + String newInstanceName = componentInstance.getName(); + if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName)) + isNameChanged = true; + Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName); + if (!isUniqueName) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName())); + } + } + if (resultOp == null) { + updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance)); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(), + updateRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null)); + } else { + // region - Update instance Groups + if (isNameChanged) { + Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId); + if (result.isRight()) + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value()); + } + // endregion + } + } + if (resultOp == null) { + String newInstanceId = updateRes.left().value().getRight(); + Optional updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst(); + + if (!updatedInstanceOptional.isPresent()) { + log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName()); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName())); + } else { + resultOp = Either.left(updatedInstanceOptional.get()); + } + + } + if (resultOp == null) { + resultOp = Either.left(componentInstanceOptional.get()); + } + return resultOp; + } + + /** + * @param oldPrefix- + * The normalized old vf name + * @param newNormailzedPrefix- + * The normalized new vf name + * @param qualifiedGroupInstanceName- + * old Group Instance Name + **/ + // modify group names + private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) { + if (qualifiedGroupInstanceName == null) { + log.info("CANNOT change group name "); + return null; + } + if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) + return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix); + return qualifiedGroupInstanceName; + } + + private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) { + oldComponentInstance.setName(newComponentInstance.getName()); + oldComponentInstance.setModificationTime(System.currentTimeMillis()); + oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString()); + if (oldComponentInstance.getGroupInstances() != null) + oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName()))); + return oldComponentInstance; + } + + public Either deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { + + Either resp = validateUserExists(userId, "delete Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either lockComponent = lockComponent(containerComponent, "deleteComponentInstance"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + // validate resource + /* + * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils + * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) { + * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; } + */ + Either resultOp = null; + try { + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); + if (resultOp.isRight()){ + return resultOp; + } + Either deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, componentInstanceId, + containerComponentType, resultOp); + if (deleteEither.isRight()){ + return deleteEither; + } + return deleteEither; + + } finally { + /* + * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service); + */ + unlockComponent(resultOp, containerComponent); + } + } + + public Either deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, + String componentInstanceId, ComponentTypeEnum containerComponentType, + Either resultOp) { + if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){ + + List pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstanceId); + if (!pathIDsToBeDeleted.isEmpty()) { + Either, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId, + pathIDsToBeDeleted); + if(deleteForwardingPathsEither.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + } + return resultOp; + } + + + private Either, ResponseFormat> deleteForwardingPaths(String serviceId, List pathIdsToDelete){ + + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if(storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value())); + } + Either, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(), + Sets.newHashSet(pathIdsToDelete)); + + if(result.isRight()) { + return Either.right(componentsUtils.getResponseFormat(result.right().value())); + } + return Either.left(result.left().value()); + } + + private List getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){ + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreForwardingPath(false); + Either forwardingPathOrigin = toscaOperationFacade + .getToscaElement(containerComponentId, filter); + Collection allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values(); + List pathIDsToBeDeleted = new ArrayList<>(); + + allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId )) + .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId())); + + return pathIDsToBeDeleted; + } + + private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, + String componentInstanceId){ + return pathDataDefinition.getPathElements().getListToscaDataDefinition() + .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || + elementDataDefinition.getToNode() + .equalsIgnoreCase(componentInstanceId)); + } + + + private Either deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) { + + Either resultOp = null; + ComponentInstance deletedInstance = null; + Either, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId); + + if (deleteRes.isRight()) { + log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } + if (resultOp == null) { + log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent); + deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent); + resultOp = Either.left(deletedInstance); + } + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) { + List groupsToUpdate = new ArrayList<>(); + for (GroupDataDefinition currGroup : containerComponent.getGroups()) { + Map members = currGroup.getMembers(); + if (members != null && members.containsKey(deletedInstance.getName())) { + members.remove(deletedInstance.getName()); + groupsToUpdate.add(currGroup); + } + } + Either, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate); + if (updateGroupsRes.isRight()) { + log.debug("Failed to delete component instance {} from group members. ", componentInstanceId); + ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType); + resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId)); + } + } + if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) { + List inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(inputsToDelete)) { + StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete); + if (deleteInputsRes != StorageOperationStatus.OK) { + log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId)); + } + } + } + return resultOp; + } + + private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) { + ComponentInstance foundInstance = null; + for (ComponentInstance instance : containerComponent.getComponentInstances()) { + if (instance.getUniqueId().equals(componentInstanceId)) { + foundInstance = instance; + containerComponent.getComponentInstances().remove(instance); + break; + } + } + findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent); + return foundInstance; + } + + private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) { + if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){ + containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList())); + } + } + + private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) { + return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId); + } + + public Either associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true); + } + + public Either associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock, + boolean createNewTransaction) { + + Either resp = validateUserExists(userId, "associate Ri To RI", inTransaction); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either resultOp = null; + + Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + if (needLock) { + Either lockComponent = lockComponent(containerComponent, "associateRIToRI"); + + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + } + + try { + + resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction); + + return resultOp; + + } finally { + if (needLock) + unlockComponent(resultOp, containerComponent); + } + } + + public Either associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) { + + log.debug("Try to create entry on graph"); + Either resultOp = null; + + Either result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef); + + if (result.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); + resultOp = Either.left(requirementCapabilityRelDef); + return resultOp; + + } else { + log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + String fromNameOrId = ""; + String toNameOrId = ""; + Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); + + toNameOrId = requirementDef.getFromNode(); + fromNameOrId = requirementDef.getFromNode(); + if (fromResult.isLeft()) { + fromNameOrId = fromResult.left().value().getName(); + } + if (toResult.isLeft()) { + toNameOrId = toResult.left().value().getName(); + } + + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); + + return resultOp; + } + + } + + public Either dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) { + Either resp = validateUserExists(userId, "dissociate RI From RI", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either resultOp = null; + Either validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + Either lockComponent = lockComponent(containerComponent, "associateRIToRI"); + + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + try { + log.debug("Try to create entry on graph"); + Either result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef); + if (result.isLeft()) { + log.debug("Enty on graph is created."); + RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value(); + resultOp = Either.left(requirementCapabilityRelDef); + return resultOp; + + } else { + + log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode()); + String fromNameOrId = ""; + String toNameOrId = ""; + Either fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode()); + Either toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode()); + + toNameOrId = requirementDef.getFromNode(); + fromNameOrId = requirementDef.getFromNode(); + if (fromResult.isLeft()) { + fromNameOrId = fromResult.left().value().getName(); + } + if (toResult.isLeft()) { + toNameOrId = toResult.left().value().getName(); + } + + resultOp = Either + .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement())); + return resultOp; + } + } finally { + unlockComponent(resultOp, containerComponent); + } + } + /** + * Allows to get relation contained in specified component according to received Id + * @param componentId + * @param relationId + * @param userId + * @param componentTypeEnum + * @return + */ + public Either getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) { + + Either resultOp = null; + try { + org.openecomp.sdc.be.model.Component containerComponent = null; + Either validateComponentExists = null; + RequirementCapabilityRelDef foundRelation = null; + + Either validateUserRes = validateUserExists(userId, "get relation by Id", false); + if (validateUserRes.isRight()) { + resultOp = Either.right(validateUserRes.right().value()); + } + if(resultOp == null){ + validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null); + if (validateComponentExists.isRight()) { + resultOp = Either.right(validateComponentExists.right().value()); + } + } + if(resultOp == null){ + containerComponent = validateComponentExists.left().value(); + List requirementCapabilityRelations = containerComponent.getComponentInstancesRelations(); + foundRelation = findRelation(relationId, requirementCapabilityRelations); + if(foundRelation == null){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId); + log.debug("Relation with id {} was not found on the component", relationId, componentId); + resultOp = Either.right(responseFormat); + } + } + if(resultOp == null){ + resultOp = setRelatedCapability(foundRelation, containerComponent); + } + if(resultOp.isLeft()){ + resultOp = setRelatedRequirement(foundRelation, containerComponent); + } + } catch (Exception e) { + log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private RequirementCapabilityRelDef findRelation(String relationId, List requirementCapabilityRelations) { + for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){ + if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){ + return relationship; + } + } + return null; + } + + private Either setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either result = null; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + String instanceId = foundRelation.getFromNode(); + Optional foundRequirement; + Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List requirements : instance.get().getRequirements().values()){ + foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst(); + if(foundRequirement.isPresent()){ + foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId()); + log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) { + return req.getName().equals(relationshipInfo.getRequirement()) && + req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && + req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId()); + } + + private Either setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) { + Either result = null; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + String instanceId = foundRelation.getToNode(); + Optional foundCapability; + Optional instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instance.isPresent()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName()); + log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } + if(result == null){ + for(List capabilities : instance.get().getCapabilities().values()){ + foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst(); + if(foundCapability.isPresent()){ + foundRelation.resolveSingleRelationship().setCapability(foundCapability.get()); + result = Either.left(foundRelation); + } + } + } + if(result == null){ + Either getfulfilledRequirementRes = + toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap)); + if(getfulfilledRequirementRes.isRight()){ + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId()); + result = Either.right(responseFormat); + } else { + foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value()); + } + } + if(result == null){ + result = Either.left(foundRelation); + } + return result; + } + + private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) { + return cap.getName().equals(relationshipInfo.getCapability()) && + cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && + cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId()); + } + + private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); + Either result; + if (eitherAttribute.isLeft()) { + log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); + + result = Either.left(instanceAttribute); + + } else { + log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); + + result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); + + } + return result; + } + + private Either createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + + Either result; + + Wrapper indexCounterWrapper = new Wrapper<>(); + Wrapper errorWrapper = new Wrapper<>(); + validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper); + + if (!errorWrapper.isEmpty()) { + result = Either.right(errorWrapper.getInnerElement()); + } else { + Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); + if (eitherAttribute.isLeft()) { + log.debug("Attribute value was added to resource instance {}", resourceInstanceId); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); + result = Either.left(instanceAttribute); + + } else { + log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value()); + result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + } + } + return result; + } + + /** + * Create Or Updates Attribute Instance + * + * @param componentTypeEnum + * @param componentId + * @param resourceInstanceId + * @param attribute + * @param userId + * @return + */ + public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { + Either result = null; + Wrapper errorWrapper = new Wrapper<>(); + + validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); + if (errorWrapper.isEmpty()) { + validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper); + } + if (errorWrapper.isEmpty()) { + validateComponentLock(componentId, componentTypeEnum, errorWrapper); + } + + try { + if (errorWrapper.isEmpty()) { + final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid()); + if (isCreate) { + result = createAttributeValue(attribute, resourceInstanceId); + } else { + result = updateAttributeValue(attribute, resourceInstanceId); + } + } else { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + } + + finally { + if (result == null || result.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) { + return StringUtils.isNotEmpty(property.getValue()) + && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) + && ComponentTypeEnum.SERVICE == componentTypeEnum; + } + + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) { + return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property)); + } + + // US833308 VLI in service - specific network_role property value logic + private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List properties) { + for (ComponentInstanceProperty property: properties) { + if (isNetworkRoleServiceProperty(property, componentTypeEnum)) { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + Either getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (getServiceResult.isRight()) { + return getServiceResult.right().value(); + } + Component service = getServiceResult.left().value(); + Optional getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny(); + if (!getInstance.isPresent()) { + return StorageOperationStatus.NOT_FOUND; + } + String prefix = service.getSystemName() + "."; + String value = property.getValue(); + if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) { + property.setValue(prefix + value); + } + } + } + return StorageOperationStatus.OK; + } + + public Either, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List properties, String userId) { + + Either, ResponseFormat> resultOp = null; + + /*-------------------------------Validations---------------------------------*/ + + Either resp = validateUserExists(userId, "create Or Update Properties Values", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // specific property value logic US833308 + StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties); + if (StorageOperationStatus.OK != fetchByIdsStatus) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus))); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + + try { + for (ComponentInstanceProperty property: properties) { + Either updatedPropertyValue = updatePropertyObjectValue(property, false); + updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance), + responseFormat -> Either.right(responseFormat)); + } + + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String capabilityType, String capabilityName) { + String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); + StringBuffer sb = new StringBuffer(componentInstanceUniqueId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); + String capKey = sb.toString(); + + Map> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) + .orElse(Collections.emptyMap()); + List capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST); + Optional cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny(); + if (cap.isPresent()) { + List capProperties = cap.get().getProperties(); + if (capProperties != null) { + Optional instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(newValue); + List path = new ArrayList<>(); + path.add(componentInstanceUniqueId); + path.add(capKey); + instanceProperty.get().setPath(path); + status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + } + } + } + + + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + List instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId()); + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + instanceProperty.get().setValue(newValue); + if (instanceProperty.isPresent()) { + status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } else { + status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property); + } + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + } + List path = new ArrayList<>(); + path.add(foundResourceInstance.getUniqueId()); + property.setPath(path); + + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private Either updatePropertyObjectValue(T property, boolean isInput) { + Either, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll(); + if (allDataTypesEither.isRight()) { + TitanOperationStatus status = allDataTypesEither.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + Map allDataTypes = allDataTypesEither.left().value(); + String innerType = null; + String propertyType = property.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = property.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + String newValue = property.getValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + if (!isInput) { + ImmutablePair pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } + return Either.left(newValue); + } + + private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) { + List instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId()); + Optional instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(input.getValue()); + status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); + } else { + status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input); + } + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + public Either, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List inputs, String userId) { + + Either, ResponseFormat> resultOp = null; + + Either resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + Either getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on service {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId)); + return resultOp; + } + + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + for (ComponentInstanceInput input: inputs) { + Either updatedInputValue = updatePropertyObjectValue(input, true); + updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance), + responseFormat -> Either.right(responseFormat)); + + } + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(inputs); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, + String userId) { + + Either resultOp = null; + + Either resp = validateUserExists(userId, "create Or Update Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + String propertyValueUid = property.getValueUniqueUid(); + + if (propertyValueUid == null) { + + Either counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId); + + if (counterRes.isRight()) { + log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Integer index = counterRes.left().value(); + Either result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true); + + if (result.isLeft()) { + log.trace("Property value was added to resource instance {}", resourceInstanceId); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + + } else { + log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + } + + } else { + Either result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + + } else { + log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + } + } + if (resultOp.isLeft()) { + StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId); + if (updateCustomizationUUID != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + } + } + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) { + + Either resultOp = null; + + Either resp = validateUserExists(userId, "create Or Update Input Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user: {} on service: {}", userId, componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", componentId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + String propertyValueUid = inputProperty.getValueUniqueUid(); + if (propertyValueUid == null) { + + Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true); + + if (counterRes.isRight()) { + log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Integer index = counterRes.left().value(); + Either result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true); + + if (result.isLeft()) { + log.debug("Property value was added to resource instance {}", resourceInstanceId); + ComponentInstanceInput instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + + } else { + Either result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid()); + ComponentInstanceInput instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + } + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + public Either deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) { + + Either resp = validateUserExists(userId, "delete Property Value", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either resultOp = null; + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + return resultOp; + } + + if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) { + log.info("Restricted operation for user {} on service {}", userId, serviceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return resultOp; + } + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock service {}", serviceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + return resultOp; + } + try { + Either result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true); + + if (result.isLeft()) { + log.debug("Property value {} was removed from graph.", propertyValueId); + ComponentInstanceProperty instanceProperty = result.left().value(); + + resultOp = Either.left(instanceProperty); + return resultOp; + + } else { + log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId); + + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value()); + + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + + return resultOp; + } + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType()); + } + + } + + private Either getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) { + + Either eitherResponse = null; + ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType); + Component component; + ResponseFormat errorResponse; + Either getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid()); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName()); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType); + errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + eitherResponse = Either.right(errorResponse); + } + if (eitherResponse == null) { + component = getComponentRes.left().value(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE; + errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString()); + eitherResponse = Either.right(errorResponse); + } + } + if (eitherResponse == null) { + eitherResponse = Either.left(getComponentRes.left().value()); + } + return eitherResponse; + } + + public Either, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam, + String containerComponentId, + String componentInstanceId, + ComponentInstance newComponentInstance) { + Either, ResponseFormat> resultOp; + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath(); + + //Fetch Component + Either validateComponentExists = + validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + Component containerComponent = validateComponentExists.left().value(); + + //Fetch current component instance + Either eitherResourceInstance = + getResourceInstanceById(containerComponent, componentInstanceId); + if (eitherResourceInstance.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); + return resultOp; + } + ComponentInstance currentResourceInstance = eitherResourceInstance.left().value(); + + //Check whether new componentInstance exists + String resourceId = newComponentInstance.getComponentUid(); + Either componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); + if (componentExistsRes.isRight()) { + log.debug("Failed to find resource ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse + (componentExistsRes.right().value()), resourceId)); + return resultOp; + } else if (!componentExistsRes.left().value()) { + log.debug("The resource {} not found ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + return resultOp; + } + + //Fetch component using new component instance uid + Either eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + Component updatedContainerComponent=eitherResourceName.left().value(); + Set toDeleteForwardingPaths = getForwardingPaths(containerComponent, + currentResourceInstance, updatedContainerComponent); + resultOp=Either.left(toDeleteForwardingPaths); + + return resultOp; + } + + private Set getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance, + Component updatedContainerComponent) { + DataForMergeHolder dataForMergeHolder=new DataForMergeHolder(); + dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId()); + + Service service = (Service) containerComponent; + ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils(); + + return forwardingPathUtils. + getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent); + } + + private ComponentParametersView getComponentParametersViewForForwardingPath() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.setIgnoreCapabiltyProperties(false); + componentParametersView.setIgnoreForwardingPath(false); + return componentParametersView; + } + + public Either changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) { + + Either resp = validateUserExists(userId, "change Component Instance Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + User user = resp.left().value(); + Either resultOp = null; + + Either validateComponentType = validateComponentType(containerComponentParam); + if (validateComponentType.isRight()) { + return Either.right(validateComponentType.right().value()); + } + + final ComponentTypeEnum containerComponentType = validateComponentType.left().value(); + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.setIgnoreCapabiltyProperties(false); + Either validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView); + if (validateComponentExists.isRight()) { + return Either.right(validateComponentExists.right().value()); + } + org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value(); + + Either validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId); + if (validateCanWorkOnComponent.isRight()) { + return Either.right(validateCanWorkOnComponent.right().value()); + } + + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId)); + return resultOp; + } + + ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value(); + + Either lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion"); + if (lockComponent.isRight()) { + return Either.right(lockComponent.right().value()); + } + + try { + + + if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) { + resultOp = Either.left(currentResourceInstance); + return resultOp; + + } + String resourceId = newComponentInstance.getComponentUid(); + + + + Either componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId); + if (componentExistsRes.isRight()) { + log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId)); + return resultOp; + } else if (!componentExistsRes.left().value()) { + log.debug("The resource {} not found ", resourceId); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + return resultOp; + } + + Either eitherOriginComponent = getInstanceOriginNode(currentResourceInstance); + + if (eitherOriginComponent.isRight()) { + resultOp = Either.right(eitherOriginComponent.right().value()); + return resultOp; + } + DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value()); + resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); + if (resultOp.isRight()) { + log.debug("failed to delete resource instance {}", resourceId); + return resultOp; + } + ComponentInstance resResourceInfo = resultOp.left().value(); + Component origComponent = null; + OriginTypeEnum originType = currentResourceInstance.getOriginType(); + if (originType == OriginTypeEnum.ServiceProxy) { + Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()))); + } + origComponent = serviceProxyOrigin.left().value(); + + StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent); + + if (fillProxyRes != StorageOperationStatus.OK) { + log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes))); + + } + newComponentInstance.setOriginType(originType); + }else{ + + + Either eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance); + + if (eitherResourceName.isRight()) { + resultOp = Either.right(eitherResourceName.right().value()); + return resultOp; + } + + origComponent = eitherResourceName.left().value(); + + newComponentInstance.setName(resResourceInfo.getName()); + } + + newComponentInstance.setInvariantName(resResourceInfo.getInvariantName()); + newComponentInstance.setPosX(resResourceInfo.getPosX()); + newComponentInstance.setPosY(resResourceInfo.getPosY()); + newComponentInstance.setDescription(resResourceInfo.getDescription()); + + resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user); + + if (resultOp.isRight()) { + log.debug("failed to create resource instance {}", resourceId); + return resultOp; + } + + ComponentInstance updatedComponentInstance = resultOp.left().value(); + if (resultOp.isRight()) { + log.debug("failed to create resource instance {}", resourceId); + return resultOp; + } + + Either mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId()); + if (mergeStatusEither.isRight()) { + return Either.right(mergeStatusEither.right().value()); + } + + ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance); + if (postChangeVersionResult != ActionStatus.OK) { + return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult)); + } + + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + Either updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter); + if (updatedComponentRes.isRight()) { + StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("Component with id {} was not found", containerComponentId); + return Either.right(responseFormat); + } + resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId()); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId())); + return resultOp; + } + resultOp = Either.left(resourceInstanceStatus.left().value()); + return resultOp; + + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + // US831698 + public Either, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) { + final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id"; + Component containerComponent = null; + + Either, ResponseFormat> resultOp = null; + try { + Either validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + return resultOp; + } + + Either validateComponentType = validateComponentType(containerComponentTypeParam); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + return resultOp; + } + + Either validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + return resultOp; + } + containerComponent = validateContainerComponentExists.left().value(); + + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + return resultOp; + } + + List instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId); + if (CollectionUtils.isEmpty(instanceProperties)) { + instanceProperties = new ArrayList<>(); + } + resultOp = Either.left(instanceProperties); + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper instaceCounterWrapper, Wrapper errorWrapper) { + Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); + + if (counterRes.isRight()) { + log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId); + StorageOperationStatus status = counterRes.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus)); + } else { + instaceCounterWrapper.setInnerElement(counterRes.left().value()); + } + + } + + /** + * updates componentInstance modificationTime + * + * @param componentInstance + * @param componentInstanceType + * @param modificationTime + * @param inTransaction + * @return + */ + public Either updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + Either result; + Either updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime, + inTransaction); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value()))); + } else { + result = Either.left(updateComponentInstanceRes.left().value()); + } + return result; + } + + public Either deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { + // TODO Add implementation + Either result = Either.left(new ComponentInstance()); + return result; + } + + public Either createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) { + // TODO Add implementation + Either result = Either.left(new ComponentInstance()); + return result; + } + + public Either changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) { + // TODO Add implementation + Either result = Either.left(new ComponentInstance()); + return result; + } + + private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) { + return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent); + } + + private Either getResourceInstanceById(Component containerComponent, String instanceId) { + + Either result = null; + List instances = containerComponent.getComponentInstances(); + Optional foundInstance = null; + if (CollectionUtils.isEmpty(instances)) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + if (result == null) { + foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if (!foundInstance.isPresent()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null) { + result = Either.left(foundInstance.get()); + } + return result; + } + + private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) { + + Long creationDate = origInstanceForUpdate.getCreationTime(); + + Long modificationTime = System.currentTimeMillis(); + resourceInstanceForUpdate.setCreationTime(creationDate); + resourceInstanceForUpdate.setModificationTime(modificationTime); + + resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) { + resourceInstanceForUpdate.setName(origInstanceForUpdate.getName()); + } + + resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName())); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) + resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) + resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) + resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName()); + + if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) + resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName()); + + if (resourceInstanceForUpdate.getOriginType() == null) { + resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType()); + } + if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) + resourceInstanceForUpdate.setIsProxy(true); + if (resourceInstanceForUpdate.getSourceModelInvariant() == null) { + resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant()); + } + if (resourceInstanceForUpdate.getSourceModelName() == null) { + resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName()); + } + if (resourceInstanceForUpdate.getSourceModelUuid() == null) { + resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid()); + } + if (resourceInstanceForUpdate.getSourceModelUid() == null) { + resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid()); + } + return resourceInstanceForUpdate; + } + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + * @param containerComponentType + * @param containerComponentId + * @param componentInstanceUniqueId + * @param capabilityType + * @param capabilityName + * @param userId + * @param ownerId + * @return + */ + public Either, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) { + + Component containerComponent = null; + + Either, ResponseFormat> resultOp = null; + try { + Either validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false); + if (validateUserExists.isRight()) { + resultOp = Either.right(validateUserExists.right().value()); + } + if(resultOp == null){ + Either validateComponentType = validateComponentType(containerComponentType); + if (validateComponentType.isRight()) { + resultOp = Either.right(validateComponentType.right().value()); + } + } + if(resultOp == null){ + Either validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()))); + } else { + containerComponent = validateContainerComponentExists.left().value(); + } + } + if(resultOp == null){ + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } else { + resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities()); + } + } + return resultOp; + } finally { + unlockComponent(resultOp, containerComponent); + } + } + + private Either, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map> instanceCapabilities) { + Either, ResponseFormat> result = null; + CapabilityDefinition foundCapability; + if (MapUtils.isNotEmpty(instanceCapabilities)) { + List capabilitiesPerType = instanceCapabilities.get(capabilityType); + if (capabilitiesPerType != null) { + Optional capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst(); + if (capabilityOpt.isPresent()) { + foundCapability = capabilityOpt.get(); + result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties()); + } + } + } + if (result == null) { + result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId); + } + return result; + } + + private Either, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) { + Either, ResponseFormat> resultOp = null; + try { + Either, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); + if(getComponentInstanceCapabilityProperties.isRight()){ + resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId)); + } else { + resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value()); + } + } catch(Exception e){ + log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e); + resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return resultOp; + } + + private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, + String capabilityType, String capabilityName, String ownerId) { + String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); + StringBuilder sb = new StringBuilder(componentInstanceUniqueId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName); + String capKey = sb.toString(); + + Map> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) + .orElse(Collections.emptyMap()); + List capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); + Optional cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny(); + if (cap.isPresent()) { + List capProperties = cap.get().getProperties(); + if (capProperties != null) { + Optional instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + StorageOperationStatus status; + if (instanceProperty.isPresent()) { + instanceProperty.get().setValue(newValue); + List path = new ArrayList<>(); + path.add(componentInstanceUniqueId); + path.add(capKey); + instanceProperty.get().setPath(path); + status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); + if (status != StorageOperationStatus.OK) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); + return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); + + } + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); + } + } + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, + List properties, String userId) { + Either, ResponseFormat> resultOp = null; + + Either resp = validateUserExists(userId, "update instance capability property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + Either getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock component {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + } + + try { + for (ComponentInstanceProperty property : properties) { + Either newPropertyValueEither = updatePropertyObjectValue(property, false); + newPropertyValueEither.bimap(updatedValue -> + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId), + responseFormat -> Either.right(responseFormat)); + } + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); + } + } + + public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, + List properties, String userId) { + Either, ResponseFormat> resultOp = null; + + Either resp = validateUserExists(userId, "update instance capability property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + if (componentTypeEnum == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + Either getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); + + if (getResourceResult.isRight()) { + log.debug("Failed to retrieve component, component id {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Component containerComponent = getResourceResult.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { + log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + Either resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); + if (resourceInstanceStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); + } + ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); + // lock resource + StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); + if (lockStatus != StorageOperationStatus.OK) { + log.debug("Failed to lock component {}", containerComponentId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); + } + + try { + for (ComponentInstanceProperty property : properties) { + Either newPropertyValueEither = updatePropertyObjectValue(property, false); + newPropertyValueEither.bimap(updatedValue -> + updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName), + responseFormat -> Either.right(responseFormat)); + } + Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); + + if (updateContainerRes.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); + resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); + return resultOp; + } + resultOp = Either.left(properties); + return resultOp; + + } finally { + if (resultOp == null || resultOp.isRight()) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + // unlock resource + graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java index f6a108cf75..90f807475f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; @@ -39,7 +31,14 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; /** * This class holds the logic of arranging resource instance on the canvas for imported VF @@ -49,240 +48,240 @@ import fj.data.Either; */ @Component("compositionBusinessLogic") public class CompositionBusinessLogic { - @Autowired - private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic; - - private static final int VFC_CANVAS_ELEMENT_SIZE = 50; - private static final int CP_CANVAS_ELEMENT_SIZE = 21; - private static final int CANVAS_WIDTH = 1000; - private static final int CANVAS_HEIGHT = 700; - private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4; - private static final double CP_RADIUS_FACTOR = 0.4; - - enum RelativePosition { - LEFT, RIGHT, UP, DOWN - }; - - protected Either, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) { - Either, ResponseFormat> result = Either.left(resource.getComponentInstances()); - - boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null - || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent(); - - if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { - // Arrange Icons In Spiral Pattern - Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); - - // Set Relative Locations According to Canvas Size - componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e)); - - // Update in DB - result = vfComponentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false); - - } - return result; - - } - - private void setRelativePosition(Entry, ComponentInstance> entry) { - int xCenter = CANVAS_WIDTH / 2; - int yCenter = CANVAS_HEIGHT / 2; - - ImmutablePair matrixPosition = entry.getKey(); - ComponentInstance componentInstance = entry.getValue(); - componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance)); - componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance)); - } - - private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) { - final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS; - double offsetedCanvasPosition; - switch (componentInstance.getOriginType()) { - case CP: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; - break; - case VL: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; - break; - case VF: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - case VFC: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - case VFCMT: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - default: - offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; - break; - } - return String.valueOf(offsetedCanvasPosition); - } - - protected Map, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) { - - Map, ComponentInstance> componentInstanceLocations = new HashMap<>(); - - List componentInstances = new ArrayList<>(); - componentInstances.addAll(resource.getComponentInstances()); - Map> connectededCps = getCpsConnectedToVFC(componentInstances, resource); - // Remove all cp that are connected from the list - componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList())); - - buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances); - buildCirclePatternForCps(componentInstanceLocations, connectededCps); - - return componentInstanceLocations; - } - - protected void buildCirclePatternForCps(Map, ComponentInstance> componentInstLocations, Map> connectedCps) { - - for (Entry> vfcCpList : connectedCps.entrySet()) { - Entry, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get(); - buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations); - } - - } - - private void buildCirclePatternForOneGroupOfCps(ImmutablePair vfcLocation, List cpsGroup, Map, ComponentInstance> componentInstLocations) { - final int numberOfCps = cpsGroup.size(); - double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0; - double currentAngle = 0; - Double xCenter = vfcLocation.getLeft(); - Double yCenter = vfcLocation.getRight(); - for (ComponentInstance currCp : cpsGroup) { - double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle); - double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle); - componentInstLocations.put(new ImmutablePair(cpXposition, cpYposition), currCp); - currentAngle += angleBetweenCps; - } - - } - - private void buildSpiralPatternForMajorComponents(Map, ComponentInstance> componentInstanceLocations, List componentInstances) { - int elementsCounter = 0; - ImmutablePair currPlacement; - ImmutablePair prevPlacement = null; - RelativePosition relationToPrevElement = null; - for (ComponentInstance curr : componentInstances) { - elementsCounter++; - if (elementsCounter == 1) { - currPlacement = new ImmutablePair(0D, 0D); - } else if (elementsCounter == 2) { - currPlacement = new ImmutablePair(-1D, 0D); - relationToPrevElement = RelativePosition.LEFT; - } else { - relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement); - currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement); - - } - - componentInstanceLocations.put(currPlacement, curr); - prevPlacement = currPlacement; - } - } - - protected Map> getCpsConnectedToVFC(List allComponentInstances, Resource vf) { - Map> vfcWithItsCps = new HashMap<>(); - List allRelations = vf.getComponentInstancesRelations(); - for (ComponentInstance curr : allComponentInstances) { - // Filters Only CPs - if (curr.getOriginType() == OriginTypeEnum.CP) { - // List Of elements the CP is connected to - List connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList()); - // Adds Only CPs Which are connected to VFC - filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList); - } - } - return vfcWithItsCps; - } - - private void filterCpConnectedToVFC(List allComponentInstances, Map> vfcWithItsCps, ComponentInstance currCP, List connectedToTheCPList) { - if (!connectedToTheCPList.isEmpty()) { - // Set Of Ids Of components Instances which are connected certain CP - Set mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet()); - - // Vfc Component instance Connected to the CP - Optional optionalVfcConnectedToCP = allComponentInstances.stream(). - // All instances connected to CP - filter(p -> mateIds.contains(p.getUniqueId())). - // Filter in only VFC connected to the CP - filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny(); - - if (optionalVfcConnectedToCP.isPresent()) { - final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get(); - if (vfcWithItsCps.containsKey(vfcWithCps)) { - vfcWithItsCps.get(vfcWithCps).add(currCP); - } else { - List cpsList = new ArrayList<>(); - cpsList.add(currCP); - vfcWithItsCps.put(vfcWithCps, cpsList); - } - } - } - } - - private RelativePosition getRelativePositionForCurrentElement(Map, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair prevPlacement) { - switch (relationToPrevElement) { - case LEFT: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP; - break; - } - case RIGHT: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN; - break; - } - case UP: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT; - break; - } - case DOWN: { - boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations); - relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT; - break; - } - default: { - throw new UnsupportedOperationException(); - } - } - return relationToPrevElement; - } - - private boolean isAdjacentElementOccupied(ImmutablePair currElement, RelativePosition adjacentElementRelationToCurrElement, Map, ComponentInstance> allElements) { - - ImmutablePair adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement); - return allElements.containsKey(adjacentElementPosition); - } - - private ImmutablePair getRelativeElementLocation(ImmutablePair currElement, RelativePosition relativeLocation) { - ImmutablePair relativeElementPosition; - switch (relativeLocation) { - - case LEFT: { - relativeElementPosition = new ImmutablePair(currElement.getLeft() - 1, currElement.getRight()); - break; - } - case RIGHT: { - relativeElementPosition = new ImmutablePair(currElement.getLeft() + 1, currElement.getRight()); - break; - } - case UP: { - relativeElementPosition = new ImmutablePair(currElement.getLeft(), currElement.getRight() + 1); - break; - } - case DOWN: { - relativeElementPosition = new ImmutablePair(currElement.getLeft(), currElement.getRight() - 1); - break; - } - default: { - throw new UnsupportedOperationException(); - } - } - return relativeElementPosition; - } + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + private static final int VFC_CANVAS_ELEMENT_SIZE = 50; + private static final int CP_CANVAS_ELEMENT_SIZE = 21; + private static final int CANVAS_WIDTH = 1000; + private static final int CANVAS_HEIGHT = 700; + private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4; + private static final double CP_RADIUS_FACTOR = 0.4; + + enum RelativePosition { + LEFT, RIGHT, UP, DOWN + }; + + protected Either, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) { + Either, ResponseFormat> result = Either.left(resource.getComponentInstances()); + + boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null + || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent(); + + if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) { + // Arrange Icons In Spiral Pattern + Map, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource); + + // Set Relative Locations According to Canvas Size + componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e)); + + // Update in DB + result = componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false); + + } + return result; + + } + + private void setRelativePosition(Entry, ComponentInstance> entry) { + int xCenter = CANVAS_WIDTH / 2; + int yCenter = CANVAS_HEIGHT / 2; + + ImmutablePair matrixPosition = entry.getKey(); + ComponentInstance componentInstance = entry.getValue(); + componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance)); + componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance)); + } + + private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) { + final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS; + double offsetedCanvasPosition; + switch (componentInstance.getOriginType()) { + case CP: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; + break; + case VL: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2; + break; + case VF: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + case VFC: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + case VFCMT: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + default: + offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2; + break; + } + return String.valueOf(offsetedCanvasPosition); + } + + protected Map, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) { + + Map, ComponentInstance> componentInstanceLocations = new HashMap<>(); + + List componentInstances = new ArrayList<>(); + componentInstances.addAll(resource.getComponentInstances()); + Map> connectededCps = getCpsConnectedToVFC(componentInstances, resource); + // Remove all cp that are connected from the list + componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList())); + + buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances); + buildCirclePatternForCps(componentInstanceLocations, connectededCps); + + return componentInstanceLocations; + } + + protected void buildCirclePatternForCps(Map, ComponentInstance> componentInstLocations, Map> connectedCps) { + + for (Entry> vfcCpList : connectedCps.entrySet()) { + Entry, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get(); + buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations); + } + + } + + private void buildCirclePatternForOneGroupOfCps(ImmutablePair vfcLocation, List cpsGroup, Map, ComponentInstance> componentInstLocations) { + final int numberOfCps = cpsGroup.size(); + double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0; + double currentAngle = 0; + Double xCenter = vfcLocation.getLeft(); + Double yCenter = vfcLocation.getRight(); + for (ComponentInstance currCp : cpsGroup) { + double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle); + double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle); + componentInstLocations.put(new ImmutablePair(cpXposition, cpYposition), currCp); + currentAngle += angleBetweenCps; + } + + } + + private void buildSpiralPatternForMajorComponents(Map, ComponentInstance> componentInstanceLocations, List componentInstances) { + int elementsCounter = 0; + ImmutablePair currPlacement; + ImmutablePair prevPlacement = null; + RelativePosition relationToPrevElement = null; + for (ComponentInstance curr : componentInstances) { + elementsCounter++; + if (elementsCounter == 1) { + currPlacement = new ImmutablePair(0D, 0D); + } else if (elementsCounter == 2) { + currPlacement = new ImmutablePair(-1D, 0D); + relationToPrevElement = RelativePosition.LEFT; + } else { + relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement); + currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement); + + } + + componentInstanceLocations.put(currPlacement, curr); + prevPlacement = currPlacement; + } + } + + protected Map> getCpsConnectedToVFC(List allComponentInstances, Resource vf) { + Map> vfcWithItsCps = new HashMap<>(); + List allRelations = vf.getComponentInstancesRelations(); + for (ComponentInstance curr : allComponentInstances) { + // Filters Only CPs + if (curr.getOriginType() == OriginTypeEnum.CP) { + // List Of elements the CP is connected to + List connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList()); + // Adds Only CPs Which are connected to VFC + filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList); + } + } + return vfcWithItsCps; + } + + private void filterCpConnectedToVFC(List allComponentInstances, Map> vfcWithItsCps, ComponentInstance currCP, List connectedToTheCPList) { + if (!connectedToTheCPList.isEmpty()) { + // Set Of Ids Of components Instances which are connected certain CP + Set mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet()); + + // Vfc Component instance Connected to the CP + Optional optionalVfcConnectedToCP = allComponentInstances.stream(). + // All instances connected to CP + filter(p -> mateIds.contains(p.getUniqueId())). + // Filter in only VFC connected to the CP + filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny(); + + if (optionalVfcConnectedToCP.isPresent()) { + final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get(); + if (vfcWithItsCps.containsKey(vfcWithCps)) { + vfcWithItsCps.get(vfcWithCps).add(currCP); + } else { + List cpsList = new ArrayList<>(); + cpsList.add(currCP); + vfcWithItsCps.put(vfcWithCps, cpsList); + } + } + } + } + + private RelativePosition getRelativePositionForCurrentElement(Map, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair prevPlacement) { + switch (relationToPrevElement) { + case LEFT: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP; + break; + } + case RIGHT: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN; + break; + } + case UP: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT; + break; + } + case DOWN: { + boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations); + relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT; + break; + } + default: { + throw new UnsupportedOperationException(); + } + } + return relationToPrevElement; + } + + private boolean isAdjacentElementOccupied(ImmutablePair currElement, RelativePosition adjacentElementRelationToCurrElement, Map, ComponentInstance> allElements) { + + ImmutablePair adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement); + return allElements.containsKey(adjacentElementPosition); + } + + private ImmutablePair getRelativeElementLocation(ImmutablePair currElement, RelativePosition relativeLocation) { + ImmutablePair relativeElementPosition; + switch (relativeLocation) { + + case LEFT: { + relativeElementPosition = new ImmutablePair(currElement.getLeft() - 1, currElement.getRight()); + break; + } + case RIGHT: { + relativeElementPosition = new ImmutablePair(currElement.getLeft() + 1, currElement.getRight()); + break; + } + case UP: { + relativeElementPosition = new ImmutablePair(currElement.getLeft(), currElement.getRight() + 1); + break; + } + case DOWN: { + relativeElementPosition = new ImmutablePair(currElement.getLeft(), currElement.getRight() - 1); + break; + } + default: { + throw new UnsupportedOperationException(); + } + } + return relativeElementPosition; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java index 9c5cefb24c..44ab4220c8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java @@ -20,8 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Date; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -42,272 +41,271 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.Date; @Component("ConsumerBusinessLogic") public class ConsumerBusinessLogic extends BaseBusinessLogic { - private static final String CONSUMER_NAME = "Consumer name"; - private static final String CONSUMER_SALT = "Consumer salt"; - private static final String CONSUMER_PW = "Consumer password"; - - @javax.annotation.Resource - private IUserBusinessLogic userAdmin; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private ConsumerOperation consumerOperation; - - @javax.annotation.Resource - private IGraphLockOperation graphLockOperation; - - private static Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class.getName()); - - public Either createConsumer(User user, ConsumerDefinition consumer) { - - Either userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - checkFieldsForOverrideAttempt(consumer); - user = userValidation.left().value(); - consumer.setLastModfierAtuid(user.getUserId()); - - Either consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - if (consumerValidationResponse.isRight()) { - ResponseFormat responseFormat = consumerValidationResponse.right().value(); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - String consumerName = consumer.getConsumerName(); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "createConsumer"); - BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName); - log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - try { - Either getResponse = consumerOperation.getCredentials(consumerName); - if (getResponse.isLeft() && getResponse.left().value() != null) { - return updateConsumer(consumer, user, true); - } - - Date date = new Date(); - consumer.setConsumerDetailsLastupdatedtime(date.getTime()); - consumer.setConsumerLastAuthenticationTime(Long.valueOf(0)); - - Either createResponse = consumerOperation.createCredentials(new ConsumerData(consumer)); - - if (createResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value())); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.right(responseFormat); - } - log.debug("Consumer created successfully!!!"); - consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } finally { - graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); - } - } - - private Either validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) { - - if (user.getUserId() == null || user.getUserId().trim().isEmpty()) { - log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - log.debug("get user from DB"); - Either eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - - user = eitherCreator.left().value(); - // validate user role - log.debug("validate user role"); - if (!user.getRole().equals(Role.ADMIN.name())) { - log.info("role {} is not allowed to perform this action", user.getRole()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); - return Either.right(responseFormat); - } - return Either.left(user); - } - - private Either validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) { - Either validateConsumerName = validateConsumerName(consumer); - if (validateConsumerName.isRight()) { - return Either.right(validateConsumerName.right().value()); - } - Either validateConsumerPassword = validateConsumerPassword(consumer); - if (validateConsumerPassword.isRight()) { - return Either.right(validateConsumerPassword.right().value()); - } - consumer = validateConsumerPassword.left().value(); - Either validateEcompUserSalt = validateConsumerSalt(consumer); - if (validateEcompUserSalt.isRight()) { - return Either.right(validateEcompUserSalt.right().value()); - } - return Either.left(consumer); - - } - - private Either validateConsumerName(ConsumerDefinition consumer) { - String name = consumer.getConsumerName(); - if (!ValidationUtils.validateStringNotEmpty(name)) { - log.debug("Consumer name cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME)); - } - if (!ValidationUtils.validateConsumerName(name)) { - log.debug("Consumer name is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); - } - if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) { - log.debug("Consumer name exceeds limit."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH))); - } - if (!ValidationUtils.isUTF8Str(name)) { - log.debug("Consumer name includes non UTF 8 characters."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); - } - - return Either.left(consumer); - } - - private Either validateConsumerPassword(ConsumerDefinition consumer) { - String password = consumer.getConsumerPassword(); - if (!ValidationUtils.validateStringNotEmpty(password)) { - log.debug("Consumer password cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW)); - } - if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) { - log.debug("Consumer password length is not valid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW)); - } - consumer.setConsumerPassword(password.toLowerCase()); - if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) { - log.debug("Consumer password is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW)); - } - - return Either.left(consumer); - } - - private Either validateConsumerSalt(ConsumerDefinition consumer) { - String salt = consumer.getConsumerSalt(); - if (!ValidationUtils.validateStringNotEmpty(salt)) { - log.debug("Consumer salt cannot be empty."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT)); - } - if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) { - log.debug("Consumer salt length is not valid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT)); - } - if (!ValidationUtils.validateConsumerPassSalt(salt)) { - log.debug("Consumer salt is invalid."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT)); - } - - return Either.left(consumer); - } - - public Either getConsumer(String consumerId, User user) { - ConsumerDefinition tmpConsumer = new ConsumerDefinition(); - tmpConsumer.setConsumerName(consumerId); - // In case of filter (southbound) call - if (user != null) { - Either userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - user = userValidation.left().value(); - } - Either getResult = consumerOperation.getCredentials(consumerId); - if (getResult.isRight()) { - ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value()); - ResponseFormat responseFormat; - if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(action, consumerId); - } else { - responseFormat = componentsUtils.getResponseFormat(action); - } - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); - return Either.right(responseFormat); - } - ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } - - public Either getConsumer(String consumerId) { - return getConsumer(consumerId, null); - } - - public Either deleteConsumer(String consumerId, User user) { - ConsumerDefinition tmpConsumer = new ConsumerDefinition(); - tmpConsumer.setConsumerName(consumerId); - Either userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - user = userValidation.left().value(); - Either deleteResult = consumerOperation.deleteCredentials(consumerId); - if (deleteResult.isRight()) { - ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value()); - ResponseFormat responseFormat; - if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(action, consumerId); - } else { - responseFormat = componentsUtils.getResponseFormat(action); - } - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); - return Either.right(responseFormat); - } - ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); - return Either.left(consumer); - } - - public Either updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) { - Either updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer)); - if (updateResult.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); - return Either.right(responseFormat); - } - consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition()); - return Either.left(consumer); - } - - private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) { - if (consumer.getConsumerDetailsLastupdatedtime() != null) { - log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application"); - } - if (consumer.getConsumerLastAuthenticationTime() != null) { - log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application"); - } - if (consumer.getLastModfierAtuid() != null) { - log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application"); - } - } + private static final String CONSUMER_NAME = "Consumer name"; + private static final String CONSUMER_SALT = "Consumer salt"; + private static final String CONSUMER_PW = "Consumer password"; + + @javax.annotation.Resource + private IUserBusinessLogic userAdmin; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private ConsumerOperation consumerOperation; + + @javax.annotation.Resource + private IGraphLockOperation graphLockOperation; + + private static final Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class); + + public Either createConsumer(User user, ConsumerDefinition consumer) { + + Either userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + checkFieldsForOverrideAttempt(consumer); + user = userValidation.left().value(); + consumer.setLastModfierAtuid(user.getUserId()); + + Either consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + if (consumerValidationResponse.isRight()) { + ResponseFormat responseFormat = consumerValidationResponse.right().value(); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + String consumerName = consumer.getConsumerName(); + StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName); + log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + try { + Either getResponse = consumerOperation.getCredentials(consumerName); + if (getResponse.isLeft() && getResponse.left().value() != null) { + return updateConsumer(consumer, user, true); + } + + Date date = new Date(); + consumer.setConsumerDetailsLastupdatedtime(date.getTime()); + consumer.setConsumerLastAuthenticationTime(Long.valueOf(0)); + + Either createResponse = consumerOperation.createCredentials(new ConsumerData(consumer)); + + if (createResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value())); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.right(responseFormat); + } + log.debug("Consumer created successfully!!!"); + consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } finally { + graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials); + } + } + + private Either validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) { + + if (user.getUserId() == null || user.getUserId().trim().isEmpty()) { + log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + log.debug("get user from DB"); + Either eitherCreator = userAdmin.getUser(user.getUserId(), false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + + user = eitherCreator.left().value(); + // validate user role + log.debug("validate user role"); + if (!user.getRole().equals(Role.ADMIN.name())) { + log.info("role {} is not allowed to perform this action", user.getRole()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user); + return Either.right(responseFormat); + } + return Either.left(user); + } + + private Either validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) { + Either validateConsumerName = validateConsumerName(consumer); + if (validateConsumerName.isRight()) { + return Either.right(validateConsumerName.right().value()); + } + Either validateConsumerPassword = validateConsumerPassword(consumer); + if (validateConsumerPassword.isRight()) { + return Either.right(validateConsumerPassword.right().value()); + } + consumer = validateConsumerPassword.left().value(); + Either validateEcompUserSalt = validateConsumerSalt(consumer); + if (validateEcompUserSalt.isRight()) { + return Either.right(validateEcompUserSalt.right().value()); + } + return Either.left(consumer); + + } + + private Either validateConsumerName(ConsumerDefinition consumer) { + String name = consumer.getConsumerName(); + if (!ValidationUtils.validateStringNotEmpty(name)) { + log.debug("Consumer name cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME)); + } + if (!ValidationUtils.validateConsumerName(name)) { + log.debug("Consumer name is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); + } + if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) { + log.debug("Consumer name exceeds limit."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH))); + } + if (!ValidationUtils.isUTF8Str(name)) { + log.debug("Consumer name includes non UTF 8 characters."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME)); + } + + return Either.left(consumer); + } + + private Either validateConsumerPassword(ConsumerDefinition consumer) { + String password = consumer.getConsumerPassword(); + if (!ValidationUtils.validateStringNotEmpty(password)) { + log.debug("Consumer password cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW)); + } + if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) { + log.debug("Consumer password length is not valid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW)); + } + consumer.setConsumerPassword(password.toLowerCase()); + if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) { + log.debug("Consumer password is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW)); + } + + return Either.left(consumer); + } + + private Either validateConsumerSalt(ConsumerDefinition consumer) { + String salt = consumer.getConsumerSalt(); + if (!ValidationUtils.validateStringNotEmpty(salt)) { + log.debug("Consumer salt cannot be empty."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT)); + } + if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) { + log.debug("Consumer salt length is not valid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT)); + } + if (!ValidationUtils.validateConsumerPassSalt(salt)) { + log.debug("Consumer salt is invalid."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT)); + } + + return Either.left(consumer); + } + + public Either getConsumer(String consumerId, User user) { + ConsumerDefinition tmpConsumer = new ConsumerDefinition(); + tmpConsumer.setConsumerName(consumerId); + // In case of filter (southbound) call + if (user != null) { + Either userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + user = userValidation.left().value(); + } + Either getResult = consumerOperation.getCredentials(consumerId); + if (getResult.isRight()) { + ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value()); + ResponseFormat responseFormat; + if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(action, consumerId); + } else { + responseFormat = componentsUtils.getResponseFormat(action); + } + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); + return Either.right(responseFormat); + } + ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } + + public Either getConsumer(String consumerId) { + return getConsumer(consumerId, null); + } + + public Either deleteConsumer(String consumerId, User user) { + ConsumerDefinition tmpConsumer = new ConsumerDefinition(); + tmpConsumer.setConsumerName(consumerId); + Either userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + user = userValidation.left().value(); + Either deleteResult = consumerOperation.deleteCredentials(consumerId); + if (deleteResult.isRight()) { + ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value()); + ResponseFormat responseFormat; + if (action == ActionStatus.ECOMP_USER_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(action, consumerId); + } else { + responseFormat = componentsUtils.getResponseFormat(action); + } + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user); + return Either.right(responseFormat); + } + ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user); + return Either.left(consumer); + } + + public Either updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) { + Either updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer)); + if (updateResult.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value())); + return Either.right(responseFormat); + } + consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition()); + return Either.left(consumer); + } + + private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) { + if (consumer.getConsumerDetailsLastupdatedtime() != null) { + log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application"); + } + if (consumer.getConsumerLastAuthenticationTime() != null) { + log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application"); + } + if (consumer.getLastModfierAtuid() != null) { + log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application"); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index 53dceb8112..6fbc22454d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -20,19 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -44,35 +32,40 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; public class CsarValidationUtils { - private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName()); + private static final Logger log = LoggerFactory.getLogger(CsarValidationUtils.class); - private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; + private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; - private static final String CSAR_VERSION = "CSAR-Version"; + private static final String CSAR_VERSION = "CSAR-Version"; - private static final String CREATED_BY = "Created-By"; + private static final String CREATED_BY = "Created-By"; - private static final String NEW_LINE_DELM = "\n"; + private static final String NEW_LINE_DELM = "\n"; - //public final static String TOSCA_METADATA_FILE = "TOSCA-Metadata/TOSCA.meta"; - public final static String TOSCA_METADATA = "TOSCA-Metadata"; - public final static String TOSCA_FILE = "TOSCA.meta"; - public final static String DEL_PATTERN = "([/\\\\]+)"; - public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA + - // Artifact Group (i.e Deployment/Informational) - DEL_PATTERN + TOSCA_FILE; + public final static String TOSCA_METADATA = "TOSCA-Metadata"; + public final static String TOSCA_FILE = "TOSCA.meta"; + public final static String DEL_PATTERN = "([/\\\\]+)"; + public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA + + // Artifact Group (i.e Deployment/Informational) + DEL_PATTERN + TOSCA_FILE; - public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; + public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; - private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; + private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS }; - public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta"; + public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta"; - public static final String TOSCA_CSAR_EXTENSION = ".csar"; + public static final String TOSCA_CSAR_EXTENSION = ".csar"; /** * Validates Csar * @param csar @@ -80,275 +73,269 @@ public class CsarValidationUtils { * @param componentsUtils * @return */ - public static Either validateCsar(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - Either validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - - removeNonUniqueArtifactsFromCsar(csar); - - log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID); - validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - return Either.left(true); - } - - private static void removeNonUniqueArtifactsFromCsar(Map csar) { - - List nonUniqueArtifactsToRemove = new ArrayList<>(); - String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]); - int numberOfArtifacts = paths.length; - for(int i = 0; i < numberOfArtifacts; ++i ){ - collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); - } - nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path)); - } - - private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List nonUniqueArtifactsToRemove) { - - String[] parsedPath = paths[currInd].split("/"); - String[] otherParsedPath; - int artifactNameInd = parsedPath.length - 1; - for(int j = currInd + 1; j < numberOfArtifacts; ++j ){ - otherParsedPath = paths[j].split("/"); - if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){ - log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ", - parsedPath[artifactNameInd], paths[currInd], paths[j]); - nonUniqueArtifactsToRemove.add(paths[j]); - } - } - } - - private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) { - boolean isEqualArtifactNames = false; - int artifactNameInd = parsedPath.length - 1; - int artifactGroupTypeInd = parsedPath.length - 3; - String groupType = parsedPath[artifactGroupTypeInd]; - String artifactName = parsedPath[artifactNameInd]; - String otherGroupType = otherParsedPath[artifactGroupTypeInd]; - String otherArtifactName = otherParsedPath[artifactNameInd]; - String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; - - if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ - isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); - } - return isEqualArtifactNames; - } - - public static Either, ResponseFormat> getToscaYaml(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - Either validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); - if (validateStatus.isRight()) { - return Either.right(validateStatus.right().value()); - } - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - byte[] toscaMetaBytes = csar.get(keyOp.get()); - Properties props = new Properties(); - try { - //props.load(new ByteArrayInputStream(toscaMetaBytes)); - String propStr = new String(toscaMetaBytes); - props.load(new StringReader(propStr.replace("\\","\\\\"))); - } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS); - String[] ops = yamlFileName.split(DEL_PATTERN); - List list = Arrays.asList(ops); - String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN)); - keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); - } - - log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID); - byte[] yamlFileBytes = csar.get(yamlFileName); - if (yamlFileBytes == null) { - log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); - } - - String yamlFileContents = new String(yamlFileBytes); - - return Either.left(new ImmutablePair(yamlFileName, yamlFileContents)); - } - - public static Either, ResponseFormat> getArtifactsMeta(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - - if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) { - log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE)); - } - - log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID); - byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE); - if (artifactsMetaBytes == null) { - log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)); - } - - String artifactsFileContents = new String(artifactsMetaBytes); - - return Either.left(new ImmutablePair(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); - } - - public static Either, ResponseFormat> getArtifactsContent(String csarUUID, Map csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { - if (!csar.containsKey(artifactPath)) { - log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); - } - - log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID); - byte[] artifactFileBytes = csar.get(artifactPath); - if (artifactFileBytes == null) { - log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID)); - } - - return Either.left(new ImmutablePair(artifactName, artifactFileBytes)); - } - - private static Either validateTOSCAMetadataFile(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - byte[] toscaMetaBytes = csar.get(keyOp.get()); - String toscaMetadata = new String(toscaMetaBytes); - String[] splited = toscaMetadata.split(NEW_LINE_DELM); - if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - /* - * if(splited.length == TOSCA_METADATA_FIELDS.length){ if(!toscaMetadata.endsWith(NEW_LINE_DELM)){ log. debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}" , csarUUID); - * BeEcompErrorManager.getInstance(). logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " +csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return - * Either.right(componentsUtils.getResponseFormat(ActionStatus. CSAR_INVALID_FORMAT, csarUUID)); } } - */ - - Either block_0Status = validateBlock_0(csarUUID, splited, componentsUtils); - if (block_0Status.isRight()) { - return Either.right(block_0Status.right().value()); - } - - return Either.left(true); - - } - - private static Either validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) { - int index = 0; - for (String toscaField : TOSCA_METADATA_FIELDS) { - - Properties props = new Properties(); - - try { - props.load(new ByteArrayInputStream(splited[index].getBytes())); - } catch (IOException e) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - if (!props.containsKey(toscaField)) { - log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - String value = props.getProperty(toscaField); - if (value == null || value.isEmpty()) { - log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - - // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format - // validation - if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) { - if (!validateTOSCAMetaProperty(value)) { - log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); - } - } - index++; - } - return Either.left(true); - } - - private static boolean validateTOSCAMetaProperty(String toscaProperty) { - final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$"; - final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING); - - Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty); - return floatMatcher.matches(); - } - - private static Either validateIsTOSCAMetadataExist(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - if (csar == null || csar.isEmpty()) { - log.debug("Error when fetching csar with ID {}", csarUUID); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID); - return Either.right(responseFormat); - } - - Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); - Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); - if(!keyOp.isPresent()){ - - log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - byte[] toscaMetaBytes = csar.get(keyOp.get()); - // && exchanged for || - if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { - log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); - BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - - return Either.left(Boolean.TRUE); - } - - public static Either getToscaYamlChecksum(Map csar, String csarUUID, ComponentsUtils componentsUtils) { - - Either, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils); - if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) { - log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID); - return Either.right(toscaYamlRes.right().value()); - } - - String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes()); - return Either.left(newCheckSum); - - } - - public static boolean isCsarPayloadName(String payloadName) { - if (payloadName == null) - return false; - return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION); - } + public static Either validateCsar(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + Either validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + + removeNonUniqueArtifactsFromCsar(csar); + + log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID); + validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + return Either.left(true); + } + + private static void removeNonUniqueArtifactsFromCsar(Map csar) { + + List nonUniqueArtifactsToRemove = new ArrayList<>(); + String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]); + int numberOfArtifacts = paths.length; + for(int i = 0; i < numberOfArtifacts; ++i ){ + collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove); + } + nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path)); + } + + private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List nonUniqueArtifactsToRemove) { + + String[] parsedPath = paths[currInd].split("/"); + String[] otherParsedPath; + int artifactNameInd = parsedPath.length - 1; + for(int j = currInd + 1; j < numberOfArtifacts; ++j ){ + otherParsedPath = paths[j].split("/"); + if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){ + log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ", + parsedPath[artifactNameInd], paths[currInd], paths[j]); + nonUniqueArtifactsToRemove.add(paths[j]); + } + } + } + + private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) { + boolean isEqualArtifactNames = false; + int artifactNameInd = parsedPath.length - 1; + int artifactGroupTypeInd = parsedPath.length - 3; + String groupType = parsedPath[artifactGroupTypeInd]; + String artifactName = parsedPath[artifactNameInd]; + String otherGroupType = otherParsedPath[artifactGroupTypeInd]; + String otherArtifactName = otherParsedPath[artifactNameInd]; + String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null; + + if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){ + isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]); + } + return isEqualArtifactNames; + } + + public static Either, ResponseFormat> getToscaYaml(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + Either validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils); + if (validateStatus.isRight()) { + return Either.right(validateStatus.right().value()); + } + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + byte[] toscaMetaBytes = csar.get(keyOp.get()); + Properties props = new Properties(); + try { + String propStr = new String(toscaMetaBytes); + props.load(new StringReader(propStr.replace("\\","\\\\"))); + } catch (IOException e) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS); + String[] ops = yamlFileName.split(DEL_PATTERN); + List list = Arrays.asList(ops); + String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN)); + keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); + } + + log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID); + byte[] yamlFileBytes = csar.get(yamlFileName); + if (yamlFileBytes == null) { + log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName)); + } + + String yamlFileContents = new String(yamlFileBytes); + + return Either.left(new ImmutablePair(yamlFileName, yamlFileContents)); + } + + public static Either, ResponseFormat> getArtifactsMeta(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + + if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) { + log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE)); + } + + log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID); + byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE); + if (artifactsMetaBytes == null) { + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)); + } + + String artifactsFileContents = new String(artifactsMetaBytes); + + return Either.left(new ImmutablePair(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents)); + } + + public static Either, ResponseFormat> getArtifactsContent(String csarUUID, Map csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) { + if (!csar.containsKey(artifactPath)) { + log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID)); + } + + log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID); + byte[] artifactFileBytes = csar.get(artifactPath); + if (artifactFileBytes == null) { + log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID)); + } + + return Either.left(new ImmutablePair(artifactName, artifactFileBytes)); + } + + private static Either validateTOSCAMetadataFile(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + byte[] toscaMetaBytes = csar.get(keyOp.get()); + String toscaMetadata = new String(toscaMetaBytes); + String[] splited = toscaMetadata.split(NEW_LINE_DELM); + if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + Either block_0Status = validateBlock_0(csarUUID, splited, componentsUtils); + if (block_0Status.isRight()) { + return Either.right(block_0Status.right().value()); + } + + return Either.left(true); + + } + + private static Either validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) { + int index = 0; + for (String toscaField : TOSCA_METADATA_FIELDS) { + + Properties props = new Properties(); + + try { + props.load(new ByteArrayInputStream(splited[index].getBytes())); + } catch (IOException e) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + if (!props.containsKey(toscaField)) { + log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + String value = props.getProperty(toscaField); + if (value == null || value.isEmpty()) { + log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + + // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format + // validation + if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) { + if (!validateTOSCAMetaProperty(value)) { + log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID)); + } + } + index++; + } + return Either.left(true); + } + + private static boolean validateTOSCAMetaProperty(String toscaProperty) { + final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$"; + final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING); + + Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty); + return floatMatcher.matches(); + } + + private static Either validateIsTOSCAMetadataExist(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + if (csar == null || csar.isEmpty()) { + log.debug("Error when fetching csar with ID {}", csarUUID); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID); + return Either.right(responseFormat); + } + + Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN); + Optional keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny(); + if(!keyOp.isPresent()){ + + log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + byte[] toscaMetaBytes = csar.get(keyOp.get()); + // && exchanged for || + if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { + log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); + BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + + return Either.left(Boolean.TRUE); + } + + public static Either getToscaYamlChecksum(Map csar, String csarUUID, ComponentsUtils componentsUtils) { + + Either, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils); + if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) { + log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID); + return Either.right(toscaYamlRes.right().value()); + } + + String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes()); + return Either.left(newCheckSum); + + } + + public static boolean isCsarPayloadName(String payloadName) { + if (payloadName == null) + return false; + return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java index e5fba0dff5..aa5cb4e2ba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; @@ -45,211 +36,214 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; @Component("dataTypeImportManager") public class DataTypeImportManager { - public static void main(String[] args) { - - List properties = new ArrayList<>(); - PropertyDefinition propertyDefintion = new PropertyDefinition(); - propertyDefintion.setName("aaa"); - properties.add(propertyDefintion); - - List allParentsProps = new ArrayList<>(); - allParentsProps.add("aaa"); - allParentsProps.add("bbb"); - - Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - System.out.println(alreadyExistPropsCollection); - - } - - private static Logger log = LoggerFactory.getLogger(DataTypeImportManager.class.getName()); - @Resource - private PropertyOperation propertyOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - public Either>, ResponseFormat> createDataTypes(String dataTypeYml) { - return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType); - } - - private Either, ActionStatus> createDataTypesFromYml(String dataTypesYml) { - - return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData)); - - } - - private Either>, ResponseFormat> createDataTypesByDao(List dataTypesToCreate) { - - return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()), - dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType)); - } - - private Either validateDataType(DataTypeDefinition dataType) { - - String dataTypeName = dataType.getName(); - List properties = dataType.getProperties(); - if (properties == null) { - // At least one parameter should be defined either in the properties - // section or at one of the parents - String derivedDataType = dataType.getDerivedFromName(); - // If there are no properties, then we can create a data type if it - // is an abstract one or it derives from non abstract data type - if ((derivedDataType == null || derivedDataType.isEmpty())) { - if (false == isAbstract(dataType.getName())) { - if (false == ToscaPropertyType.isScalarType(dataTypeName)) { - log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); - - return Either.right(responseFormat); - } - } - } else { - // if it is not a scalar data type and it derives from abstract - // data type, we should reject the request. - if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) { - log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); - - return Either.right(responseFormat); - } - } - } else { - // properties tag cannot be empty - if (properties.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null); - - return Either.right(responseFormat); - } - - // check no duplicates - Set collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet()); - if (collect != null) { - if (properties.size() != collect.size()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null); - - return Either.right(responseFormat); - } - } - - List propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList()); - if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) { - log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType); - - return Either.right(responseFormat); - } - } - - String derivedDataType = dataType.getDerivedFromName(); - if (derivedDataType != null) { - Either derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true); - if (derivedDataTypeByName.isRight()) { - StorageOperationStatus status = derivedDataTypeByName.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null); - - return Either.right(responseFormat); - } else { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null); - - return Either.right(responseFormat); - - } - } else { - - DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value(); - if (properties != null && properties.isEmpty() == false) { - - if (true == isScalarType(derivedDataTypeDef)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null); - - return Either.right(responseFormat); - } - - Set allParentsProps = new HashSet<>(); - do { - List currentParentsProps = derivedDataTypeDef.getProperties(); - if (currentParentsProps != null) { - for (PropertyDefinition propertyDefinition : currentParentsProps) { - allParentsProps.add(propertyDefinition.getName()); - } - } - derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom(); - } while (derivedDataTypeDef != null); - - // Check that no property is already defined in one of the - // ancestors - Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) { - List duplicateProps = new ArrayList<>(); - duplicateProps.addAll(alreadyExistPropsCollection); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); - - return Either.right(responseFormat); - } - - } - } - } - return Either.left(ActionStatus.OK); - } - - private boolean isAbstract(String dataTypeName) { - - ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); - - return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true; - - } - - private boolean isScalarType(DataTypeDefinition dataTypeDef) { - - boolean isScalar = false; - DataTypeDefinition dataType = dataTypeDef; - - while (dataType != null) { - - String name = dataType.getName(); - if (ToscaPropertyType.isScalarType(name)) { - isScalar = true; - break; - } + public static void main(String[] args) { + + List properties = new ArrayList<>(); + PropertyDefinition propertyDefintion = new PropertyDefinition(); + propertyDefintion.setName("aaa"); + properties.add(propertyDefintion); + + List allParentsProps = new ArrayList<>(); + allParentsProps.add("aaa"); + allParentsProps.add("bbb"); + + Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + System.out.println(alreadyExistPropsCollection); + + } + + private static final Logger log = LoggerFactory.getLogger(DataTypeImportManager.class); + @Resource + private PropertyOperation propertyOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + public Either>, ResponseFormat> createDataTypes(String dataTypeYml) { + return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType); + } + + private Either, ActionStatus> createDataTypesFromYml(String dataTypesYml) { + + return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData)); + + } + + private Either>, ResponseFormat> createDataTypesByDao(List dataTypesToCreate) { + + return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()), + dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType)); + } + + private Either validateDataType(DataTypeDefinition dataType) { + + String dataTypeName = dataType.getName(); + List properties = dataType.getProperties(); + if (properties == null) { + // At least one parameter should be defined either in the properties + // section or at one of the parents + String derivedDataType = dataType.getDerivedFromName(); + // If there are no properties, then we can create a data type if it + // is an abstract one or it derives from non abstract data type + if (derivedDataType == null || derivedDataType.isEmpty()) { + if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) { + log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); + return Either.right(responseFormat); + } + } else { + // if it is not a scalar data type and it derives from abstract + // data type, we should reject the request. + if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) { + log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null); + return Either.right(responseFormat); + } + } + } else { + // properties tag cannot be empty + if (properties.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null); + + return Either.right(responseFormat); + } + + // check no duplicates + Set collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet()); + if (collect != null) { + if (properties.size() != collect.size()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null); + + return Either.right(responseFormat); + } + } + + List propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList()); + if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) { + log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType); + + return Either.right(responseFormat); + } + } + + String derivedDataType = dataType.getDerivedFromName(); + if (derivedDataType != null) { + Either derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true); + if (derivedDataTypeByName.isRight()) { + StorageOperationStatus status = derivedDataTypeByName.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null); + + return Either.right(responseFormat); + } else { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null); + + return Either.right(responseFormat); + + } + } else { + + DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value(); + if (properties != null && properties.isEmpty() == false) { + + if (true == isScalarType(derivedDataTypeDef)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null); + + return Either.right(responseFormat); + } + + Set allParentsProps = new HashSet<>(); + do { + List currentParentsProps = derivedDataTypeDef.getProperties(); + if (currentParentsProps != null) { + for (PropertyDefinition propertyDefinition : currentParentsProps) { + allParentsProps.add(propertyDefinition.getName()); + } + } + derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom(); + } while (derivedDataTypeDef != null); + + // Check that no property is already defined in one of the + // ancestors + Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) { + List duplicateProps = new ArrayList<>(); + duplicateProps.addAll(alreadyExistPropsCollection); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps); + + return Either.right(responseFormat); + } + + } + } + } + return Either.left(ActionStatus.OK); + } + + private boolean isAbstract(String dataTypeName) { + + ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName); + + return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true; + + } + + private boolean isScalarType(DataTypeDefinition dataTypeDef) { + + boolean isScalar = false; + DataTypeDefinition dataType = dataTypeDef; + + while (dataType != null) { + + String name = dataType.getName(); + if (ToscaPropertyType.isScalarType(name)) { + isScalar = true; + break; + } - dataType = dataType.getDerivedFrom(); - } + dataType = dataType.getDerivedFrom(); + } - return isScalar; - } + return isScalar; + } - private DataTypeDefinition createDataType(String dataTypeName, Map toscaJson) { - DataTypeDefinition dataType = new DataTypeDefinition(); + private DataTypeDefinition createDataType(String dataTypeName, Map toscaJson) { + DataTypeDefinition dataType = new DataTypeDefinition(); - dataType.setName(dataTypeName); + dataType.setName(dataTypeName); - if (toscaJson != null) { - // Description - final Consumer descriptionSetter = description -> dataType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values)); + if (toscaJson != null) { + // Description + final Consumer descriptionSetter = description -> dataType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values)); - setConstraints(toscaJson, dataType); - } - return dataType; - } + setConstraints(toscaJson, dataType); + } + return dataType; + } - private void setConstraints(Map toscaJson, DataTypeDefinition dataType) { - // TODO Auto-generated method stub + private void setConstraints(Map toscaJson, DataTypeDefinition dataType) { + // TODO Auto-generated method stub - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java index be3ac13cc9..5469d79653 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -46,172 +41,170 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; @Component("distributionMonitoringBusinessLogic") public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic { - private static final String DEPLOYED = "Deployed"; - - private static final String ERROR = "Error"; - - private static final String DISTRIBUTED = "Distributed"; - - private static final String IN_PROGRESS = "In Progress"; - - private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName()); - - // @javax.annotation.Resource - // private AuditingDao auditingDao; - - @Autowired - private AuditCassandraDao cassandraDao; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - public DistributionMonitoringBusinessLogic() { - } - - public Either getListOfDistributionStatus(String did, String userId) { - - Either resp = validateUserExists(userId, "get List Of Distribution Status", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.trace("getListOfDistributionStatus for did {}", did); - Either, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); - if (distributionStatus.isRight()) { - log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value()); - return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did)); - } - List distribStatusInfoList = new ArrayList(); - List distributionStatusEventList = distributionStatus.left().value(); - if (distributionStatusEventList != null) { - for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) { - distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); - } - } - - DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse(); - distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList); - log.trace("list statuses for did {} is {} ", did, distribStatusInfoList); - return Either.left(distributionStatusListResponse); - } - - public Either getListOfDistributionServiceStatus(String serviceUuid, String userId) { - Either resp = validateUserExists(userId, "get List Of Distribution Service Status", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); - Either, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); - if (status.isRight()) { - log.debug("failed to find service distribution statuses. error: {}", status); - return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid)); - } - List distribStatusInfoList = new ArrayList(); - List distributionStatusEventList = status.left().value(); - distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList); - DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce(); - distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList); - return Either.left(distributionStatusListResponse); - } - - private List handleAuditingDaoResponse(List distribStatusInfoList) { - List reslist = new ArrayList(); - Map> serviceDidMap = createServiceDidMap(distribStatusInfoList); - Set didSet = serviceDidMap.keySet(); - for (String did : didSet) { - DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo(); - distributionStatusOfServiceInfo.setDistributionID(did); - String dReguestStatus = ""; - String dNotifyStatus = ""; - boolean isResult = false; - List auditingGenericEventList = serviceDidMap.get(did); - ESTimeBasedEvent resAuditingGenericEvent = null; - for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { - auditingGenericEvent.fillFields(); - - String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName()); - Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName()); - if (modifierUserId != null) { - distributionStatusOfServiceInfo.setUserId((String) modifierUserId); - } - - if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) { - - isResult = true; - resAuditingGenericEvent = auditingGenericEvent; - break; - } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) { - dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent); - } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) { - dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent); - } - - resAuditingGenericEvent = auditingGenericEvent; - - } - distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName())); - - if (!isResult) { - if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) { - if (dNotifyStatus.isEmpty()) { - distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS); - - } else { - if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) - distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED); - else - distributionStatusOfServiceInfo.setDeployementStatus(ERROR); - } - } else - distributionStatusOfServiceInfo.setDeployementStatus(ERROR); - } else - distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED); - reslist.add(distributionStatusOfServiceInfo); - } - - return reslist; - } - - private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) { - String status = ""; - Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName()); - if (requestStatus instanceof String) { - status = (String) requestStatus; - } - return status; - } - - private Map> createServiceDidMap(List distribStatusInfoList) { - - Map> serviceDidMap = new HashMap>(); - for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) { - List auditingGenericEventList = null; - String did = ""; - auditingGenericEvent.fillFields(); - - Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName()); - if (didValue != null) { - did = (String) didValue; - } - - if (!did.isEmpty()) { - if (serviceDidMap.containsKey(did)) { - auditingGenericEventList = serviceDidMap.get(did); - } - if (auditingGenericEventList == null) { - auditingGenericEventList = new ArrayList(); - - } - auditingGenericEventList.add(auditingGenericEvent); - serviceDidMap.put(did, auditingGenericEventList); - } - } - return serviceDidMap; - } + private static final String DEPLOYED = "Deployed"; + + private static final String ERROR = "Error"; + + private static final String DISTRIBUTED = "Distributed"; + + private static final String IN_PROGRESS = "In Progress"; + + private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class); + + + @Autowired + private AuditCassandraDao cassandraDao; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + public DistributionMonitoringBusinessLogic() { + } + + public Either getListOfDistributionStatus(String did, String userId) { + + Either resp = validateUserExists(userId, "get List Of Distribution Status", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.trace("getListOfDistributionStatus for did {}", did); + Either, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did); + if (distributionStatus.isRight()) { + log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value()); + return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did)); + } + List distribStatusInfoList = new ArrayList(); + List distributionStatusEventList = distributionStatus.left().value(); + if (distributionStatusEventList != null) { + for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) { + distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent)); + } + } + + DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse(); + distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList); + log.trace("list statuses for did {} is {} ", did, distribStatusInfoList); + return Either.left(distributionStatusListResponse); + } + + public Either getListOfDistributionServiceStatus(String serviceUuid, String userId) { + Either resp = validateUserExists(userId, "get List Of Distribution Service Status", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid); + Either, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid); + if (status.isRight()) { + log.debug("failed to find service distribution statuses. error: {}", status); + return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid)); + } + List distribStatusInfoList = new ArrayList(); + List distributionStatusEventList = status.left().value(); + distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList); + DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce(); + distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList); + return Either.left(distributionStatusListResponse); + } + + private List handleAuditingDaoResponse(List distribStatusInfoList) { + List reslist = new ArrayList(); + Map> serviceDidMap = createServiceDidMap(distribStatusInfoList); + Set didSet = serviceDidMap.keySet(); + for (String did : didSet) { + DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo(); + distributionStatusOfServiceInfo.setDistributionID(did); + String dReguestStatus = ""; + String dNotifyStatus = ""; + boolean isResult = false; + List auditingGenericEventList = serviceDidMap.get(did); + ESTimeBasedEvent resAuditingGenericEvent = null; + for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) { + auditingGenericEvent.fillFields(); + + String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName()); + Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName()); + if (modifierUserId != null) { + distributionStatusOfServiceInfo.setUserId((String) modifierUserId); + } + + if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) { + + isResult = true; + resAuditingGenericEvent = auditingGenericEvent; + break; + } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) { + dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent); + } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) { + dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent); + } + + resAuditingGenericEvent = auditingGenericEvent; + + } + distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName())); + + if (!isResult) { + if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) { + if (dNotifyStatus.isEmpty()) { + distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS); + + } else { + if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) + distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED); + else + distributionStatusOfServiceInfo.setDeployementStatus(ERROR); + } + } else + distributionStatusOfServiceInfo.setDeployementStatus(ERROR); + } else + distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED); + reslist.add(distributionStatusOfServiceInfo); + } + + return reslist; + } + + private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) { + String status = ""; + Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName()); + if (requestStatus instanceof String) { + status = (String) requestStatus; + } + return status; + } + + private Map> createServiceDidMap(List distribStatusInfoList) { + + Map> serviceDidMap = new HashMap>(); + for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) { + List auditingGenericEventList = null; + String did = ""; + auditingGenericEvent.fillFields(); + + Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName()); + if (didValue != null) { + did = (String) didValue; + } + + if (!did.isEmpty()) { + if (serviceDidMap.containsKey(did)) { + auditingGenericEventList = serviceDidMap.get(did); + } + if (auditingGenericEventList == null) { + auditingGenericEventList = new ArrayList(); + + } + auditingGenericEventList.add(auditingGenericEvent); + serviceDidMap.put(did, auditingGenericEventList); + } + } + return serviceDidMap; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 54bed5ae56..ac72c98252 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -20,20 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; @@ -54,7 +41,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactType; @@ -65,10 +51,10 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.PropertyScope; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.ResourceMetadataDefinition; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.Tag; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -91,1328 +77,1297 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.thinkaurelius.titan.core.TitanGraph; - -import fj.data.Either; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("elementsBusinessLogic") public class ElementBusinessLogic extends BaseBusinessLogic { - private static Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class.getName()); - - @javax.annotation.Resource - private IElementOperation elementOperation; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private UserBusinessLogic userAdminManager; - - /** - * - * @param user - * @return - */ - public Either>, ResponseFormat> getFollowed(User user) { - // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains - Either>, ResponseFormat> response = null; - // Used for returning as the code requires. - Either>, ResponseFormat> arrayResponse = null; - - // Getting the role - String role = user.getRole(); - String userId = null; - Role currentRole = Role.valueOf(role); - - switch (currentRole) { - case DESIGNER: - userId = user.getUserId(); - response = handleDesigner(userId); - break; - - case TESTER: - userId = user.getUserId(); - response = handleTester(userId); - break; - - case GOVERNOR: - userId = user.getUserId(); - response = handleGovernor(userId); - break; - - case OPS: - userId = user.getUserId(); - response = handleOps(userId); - break; - - case PRODUCT_STRATEGIST: - userId = user.getUserId(); - response = handleProductStrategist(userId); - break; - - case PRODUCT_MANAGER: - userId = user.getUserId(); - response = handleProductManager(userId); - break; - - case ADMIN: - response = handleAdmin(); - break; - - default: - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - break; - } - //converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice) - return convertedToListResponse(response); - - } - - private Either>,ResponseFormat> convertedToListResponse(Either>, ResponseFormat> setResponse) { - - Map> arrayResponse = new HashMap<>(); - if (setResponse.isLeft()) { - for (Map.Entry> entry : setResponse.left().value().entrySet()) { - arrayResponse.put(entry.getKey(), (new ArrayList(new HashSet(entry.getValue())))); - } - return Either.left(arrayResponse); - } - return Either.right(setResponse.right().value()); - } - - private Either>, ResponseFormat> handleAdmin() { - Either>, ResponseFormat> response; - // userId should stay null - Set lifecycleStates = new HashSet(); - Set lastStateStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates); - return response; - } - - private Either>, ResponseFormat> handleDesigner(String userId) { - Set lifecycleStates = new HashSet(); - Set lastStateStates = new HashSet(); - Either>, ResponseFormat> response; - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates); - return response; - } - - private Either>, ResponseFormat> handleGovernor(String userId) { - Either>, ResponseFormat> result = handleFollowedCertifiedServices(null); - return result; - } - - private Either>, ResponseFormat> handleProductStrategist(String userId) { - // Should be empty list according to Ella, 13/03/16 - Map> result = new HashMap>(); - result.put("products", new HashSet<>()); - return Either.left(result); - } - - private Either>, ResponseFormat> handleProductManager(String userId) { - Set lifecycleStates = new HashSet(); - Set lastStateStates = new HashSet(); - Either>, ResponseFormat> response; - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.CERTIFIED); - // more states - lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - response = getFollowedProducts(userId, lifecycleStates, lastStateStates); - return response; - } - - private Either>, ResponseFormat> handleOps(String userId) { - Set distStatus = new HashSet(); - distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); - distStatus.add(DistributionStatusEnum.DISTRIBUTED); - - Either>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus); - return result; - } - - private Either>, ResponseFormat> handleFollowedCertifiedServices(Set distStatus) { - - Either, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); - if (services.isLeft()) { - Map> result = new HashMap<>(); - Set set = new HashSet<>(); - set.addAll(services.left().value()); - result.put("services", set); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); - } - } - - private Either>, ResponseFormat> handleTester(String userId) { - Set lifecycleStates = new HashSet(); - lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null); - - return result; - } - - private Either>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set lifecycleStates, Set lastStateStates) { - - try { - Either, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); - - if (resources.isLeft()) { - Either, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); - if (services.isLeft()) { - Map> result = new HashMap>(); - result.put("services", services.left().value()); - result.put("resources", resources.left().value()); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); - } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); - } - } finally { - titanDao.commit(); - } - } - - private Either>, ResponseFormat> getFollowedProducts(String userId, Set lifecycleStates, Set lastStateStates) { - Either, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); - if (products.isLeft()) { - Map> result = new HashMap<>(); - result.put("products", products.left().value()); - return Either.left(result); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value()))); - } - } - - /* - * New categories flow - start - */ - public Either, ActionStatus> getAllResourceCategories() { - return elementOperation.getAllResourceCategories(); - } - - public Either, ActionStatus> getAllServiceCategories() { - return elementOperation.getAllServiceCategories(); - } - - public Either createCategory(CategoryDefinition category, String componentTypeParamName, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY; - - User user = new User(); - Either validateUser = validateUser(userId); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - String currCategoryName = (category == null ? null : category.getName()); - handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (category == null) { - log.debug("Category json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String categoryName = category.getName(); - // For auditing of failures we need the original non-normalized name - String origCategoryName = categoryName; - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) { - log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) { - log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - category.setName(categoryName); - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); - category.setNormalizedName(normalizedName); - - NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType); - - Either categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName); - if (categoryUniqueEither.isRight()) { - log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value()); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isCategoryUnique = categoryUniqueEither.left().value(); - if (!isCategoryUnique) { - log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either createCategoryByType = elementOperation.createCategory(category, nodeType); - if (createCategoryByType.isRight()) { - log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); - handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); - return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value())); - } - category = createCategoryByType.left().value(); - log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType); - return Either.left(category); - } - - public Either createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY; - // For auditing - String parentCategoryName = parentCategoryId; - - if (subCategory == null) { - log.debug("Sub-category json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String subCategoryName = subCategory.getName(); - // For auditing of failures we need the original non-normalized name - String origSubCategoryName = subCategoryName; - - User user = new User(); - Either validateUser = validateUserExists(userId, "createSubCategory", false); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); - if (validateComponentType.isRight()) { - log.debug("Validation of component type for sub-category failed"); - ResponseFormat responseFormat = validateComponentType.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - - CategoryDefinition categoryDefinition; - Either validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum); - if (validateCategoryExists.isRight()) { - log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId); - ResponseFormat responseFormat = validateCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryDefinition = validateCategoryExists.left().value(); - parentCategoryName = categoryDefinition.getName(); - - if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) { - log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) { - log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName); - subCategory.setNormalizedName(normalizedName); - - // Uniqueness under this category - Either subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId); - if (subCategoryUniqueForCategory.isRight()) { - log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isSubUnique = subCategoryUniqueForCategory.left().value(); - if (!isSubUnique) { - log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - // Setting name of subcategory to fit the similar subcategory name - // ignoring cases. - // For example if Network-->kUKU exists for service category Network, - // and user is trying to create Router-->Kuku for service category - // Router, - // his subcategory name will be Router-->kUKU. - Either subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName); - if (subCategoryUniqueForType.isRight()) { - log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value(); - if (subCategoryDefinition != null) { - subCategoryName = subCategoryDefinition.getName(); - } - - subCategory.setName(subCategoryName); - ///////////////////////////////////////////// Validations end - - Either createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType); - if (createSubCategory.isRight()) { - log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); - return Either.right(responseFormat); - } - - SubCategoryDefinition subCategoryCreated = createSubCategory.left().value(); - log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType); - return Either.left(subCategoryCreated); - } - - public Either createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) { - - AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING; - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue()); - CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING; - // For auditing - String parentCategoryName = grandParentCategoryId; - String parentSubCategoryName = parentSubCategoryId; - - User user; - Either validateUser = validateUserExists(userId, "create Grouping", false); - if (validateUser.isRight()) { - log.debug("Validation of user failed, userId {}", userId); - ResponseFormat responseFormat = validateUser.right().value(); - user = new User(); - user.setUserId(userId); - String groupingNameForAudit = (grouping == null ? null : grouping.getName()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType); - return Either.right(responseFormat); - } - - user = validateUser.left().value(); - - if (grouping == null) { - log.debug("Grouping json is invalid"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType); - return Either.right(responseFormat); - } - - String groupingName = grouping.getName(); - // For auditing of failures we need the original non-normalized name - String origGroupingName = groupingName; - - if (componentTypeEnum == null) { - log.debug("Component type {} is invalid", componentTypeParamName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); - if (validateComponentType.isRight()) { - log.debug("Validation of component type for grouping failed"); - ResponseFormat responseFormat = validateComponentType.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Either validateUserRole = validateUserRole(user, componentTypeEnum); - if (validateUserRole.isRight()) { - log.debug("Validation of user role failed, userId {}", userId); - ResponseFormat responseFormat = validateUserRole.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); - - // Validate category - CategoryDefinition categoryDefinition; - Either validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum); - if (validateCategoryExists.isRight()) { - log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId); - ResponseFormat responseFormat = validateCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - categoryDefinition = validateCategoryExists.left().value(); - parentCategoryName = categoryDefinition.getName(); - - // Validate subcategory - SubCategoryDefinition subCategoryDefinition; - Either validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum); - if (validateSubCategoryExists.isRight()) { - log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId); - ResponseFormat responseFormat = validateSubCategoryExists.right().value(); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - subCategoryDefinition = validateSubCategoryExists.left().value(); - parentSubCategoryName = subCategoryDefinition.getName(); - - if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) { - log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName); - - if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) { - log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName); - grouping.setNormalizedName(normalizedName); - - // Uniqueness under this category - Either groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId); - if (groupingUniqueForSubCategory.isRight()) { - log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value(); - if (!isGroupingUnique) { - log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - // Setting name of grouping to fit the similar grouping name ignoring - // cases. - // For example if Network-->kUKU exists for service sub-category - // Network, and user is trying to create grouping Router-->Kuku for - // service sub-category Router, - // his grouping name will be Router-->kUKU. - Either groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName); - if (groupingUniqueForType.isRight()) { - log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - GroupingDefinition groupingDefinition = groupingUniqueForType.left().value(); - if (groupingDefinition != null) { - groupingName = groupingDefinition.getName(); - } - - grouping.setName(groupingName); - ///////////////////////////////////////////// Validations end - - Either createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType); - if (createGrouping.isRight()) { - log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value()); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); - return Either.right(responseFormat); - } - - GroupingDefinition groupingCreated = createGrouping.left().value(); - log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType); - return Either.left(groupingCreated); - } - - public Either, ResponseFormat> getAllCategories(String componentType, String userId) { - AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; - ResponseFormat responseFormat; - User user = new User(); - if (userId == null) { - user.setUserId("UNKNOWN"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - - Either validateUser = validateUserExists(userId, "get All Categories", false); - if (validateUser.isRight()) { - user.setUserId(userId); - log.debug("Validation of user failed, userId {}", userId); - responseFormat = validateUser.right().value(); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - user = validateUser.left().value(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum == null) { - log.debug("Cannot create category for component type {}", componentType); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type"); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - Either, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false); - if (getAllCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.right(responseFormat); - } - List categories = getAllCategoriesByType.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); - return Either.left(categories); - } - - public Either getAllCategories(String userId) { - AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; - ResponseFormat responseFormat; - UiCategories categories = new UiCategories(); - - Either userResponse = validateUserExists(userId, "get all categories", false); - - if (userResponse.isRight()) { - return Either.right(userResponse.right().value()); - } - User user = userResponse.left().value(); - - //GET resource categories - Either, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); - if (getResourceCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat); - return Either.right(responseFormat); - } - categories.setResourceCategories(getResourceCategoriesByType.left().value()); - - //GET service categories - Either, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false); - if (getServiceCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); - return Either.right(responseFormat); - } - categories.setServiceCategories(getServiceCategoriesByType.left().value()); - - //GET product categories - Either, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); - if (getProductCategoriesByType.isRight()) { - responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); - componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); - return Either.right(responseFormat); - } - - categories.setProductCategories(getProductCategoriesByType.left().value()); - return Either.left(categories); - - } - - public Either deleteCategory(String categoryId, String componentTypeParamName, String userId) { - - Either resp = validateUserExists(userId, "delete Category", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot create category for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); - - Either deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId); - if (deleteCategoryByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value())); - } - CategoryDefinition category = deleteCategoryByType.left().value(); - log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId()); - return Either.left(category); - } - - public Either deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) { - - Either resp = validateUserExists(userId, "delete Sub Category", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot delete sub-category for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); - - Either deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId); - if (deleteSubCategoryByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value())); - } - SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value(); - log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId()); - return Either.left(subCategory); - } - - public Either deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) { - - Either resp = validateUserExists(userId, "delete Grouping", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); - if (componentTypeEnum == null) { - log.debug("Cannot delete grouping for component type {}", componentTypeParamName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); - - Either deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId); - if (deleteGroupingByType.isRight()) { - // auditing, logging here... - return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value())); - } - GroupingDefinition deletedGrouping = deleteGroupingByType.left().value(); - log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId()); - return Either.left(deletedGrouping); - } - - private Either validateUser(String userId) { - - // validate user exists - if (userId == null) { - log.debug("UserId is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); - } - - Either userResult = userAdminManager.getUser(userId, false); - if (userResult.isRight()) { - ResponseFormat responseFormat; - if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - log.debug("Not authorized user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - log.debug("Failed to authorize user, userId = {}", userId); - responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); - } - - return Either.right(responseFormat); - } - return Either.left(userResult.left().value()); - // ========================================- - } - - private Either validateUserRole(User user, ComponentTypeEnum componentTypeEnum) { - String role = user.getRole(); - boolean validAdminAction = (role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE)); - boolean validProductAction = (role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT)); - - if (!(validAdminAction || validProductAction)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) { - boolean validResourceAction = (componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY)); - boolean validServiceAction = (componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY); - boolean validProductAction = (componentType == ComponentTypeEnum.PRODUCT); // can - // be - // any - // category - // type - - if (!(validResourceAction || validServiceAction || validProductAction)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType); - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) { - Either categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId); - if (categoryByTypeAndId.isRight()) { - log.debug("Failed to fetch parent category, parent categoryId {}", categoryId); - ActionStatus actionStatus = categoryByTypeAndId.right().value(); - ResponseFormat responseFormat; - if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), ""); - } else { - responseFormat = componentsUtils.getResponseFormat(actionStatus); - } - return Either.right(responseFormat); - } - return Either.left(categoryByTypeAndId.left().value()); - } - - private Either validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) { - Either subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId); - if (subCategoryByTypeAndId.isRight()) { - log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId); - ActionStatus actionStatus = subCategoryByTypeAndId.right().value(); - ResponseFormat responseFormat; - if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { - responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), ""); - } else { - responseFormat = componentsUtils.getResponseFormat(actionStatus); - } - return Either.right(responseFormat); - } - return Either.left(subCategoryByTypeAndId.left().value()); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType); - } - - private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) { - componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType); - } - - /* - * New categories flow - end - */ - - public Either, ActionStatus> getAllTags(String userId) { - Either resp = validateUserExistsActionStatus(userId, "get All Tags"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllTags(); - } - - public Either, ActionStatus> getAllPropertyScopes(String userId) { - Either resp = validateUserExistsActionStatus(userId, "get All Property Scopes"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllPropertyScopes(); - } - - public Either, ActionStatus> getAllArtifactTypes(String userId) { - Either resp = validateUserExistsActionStatus(userId, "get All Artifact Types"); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - return elementOperation.getAllArtifactTypes(); - } - - public Either, ActionStatus> getAllDeploymentArtifactTypes() { - return elementOperation.getAllDeploymentArtifactTypes(); - } - - public Either getDefaultHeatTimeout() { - return elementOperation.getDefaultHeatTimeout(); - } - - public Either>, ResponseFormat> getCatalogComponents(String userId, List excludeTypes) { - Either resp = validateUserExists(userId, "get Catalog Components", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Map> resMap = new HashMap<>(); - - Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE,excludeTypes, true); - if (resResources.isLeft()) { - Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE,excludeTypes, true); - if (resServices.isLeft()) { - // Either, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); - // if (resProducts.isLeft()) { - resMap.put("resources", resResources.left().value()); - resMap.put("services", resServices.left().value()); - resMap.put("products", new ArrayList<>()); - - return Either.left(resMap); - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resServices.right().value()))); - } - } else { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resResources.right().value()))); - } - } - - public Either, ResponseFormat> getFilteredCatalogComponents(String assetType, Map filters, String query) { - ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); - - if (query != null) { - Optional invalidFilter = findInvalidFilter(query, assetTypeEnum); - if (invalidFilter.isPresent()) { - log.debug("getFilteredAssetList: invalid filter key"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString())); - } - } - - if (filters == null || filters.isEmpty()) { - Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum,null, false); - if(componentsList.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); - } - return Either.left(componentsList.left().value()); - } - - Either, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false); - - // category hierarchy mismatch or category/subCategory/distributionStatus not found - if (result.isRight()) { - List params = getErrorResponseParams(filters, assetTypeEnum); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2))); - } - if (result.left().value().isEmpty()) {// no assets found for requested - // criteria - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query)); - } - return Either.left(result.left().value()); - } - - private Either, StorageOperationStatus> getFilteredComponents(Map filters, ComponentTypeEnum assetType, boolean inTransaction) { - Either, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); - if(assetType == ComponentTypeEnum.RESOURCE){ - - assetResult = getFilteredResouces(filters, inTransaction); - - } else if (assetType == ComponentTypeEnum.SERVICE){ - - assetResult = getFilteredServices(filters, inTransaction); - } - return assetResult; - } - - private Either, StorageOperationStatus> getFilteredServices(Map filters, boolean inTransaction) { - - Either, StorageOperationStatus> components = null; - - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); - DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); - if (distributionStatus != null && distEnum == null) { - filters.remove(FilterKeyEnum.CATEGORY); - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - - if (categoryName != null) { // primary filter - components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); - if (components.isLeft() && distEnum != null) {// secondary filter - Predicate statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); - return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); - } - filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); - return components; - } - - Set distStatusSet = new HashSet<>(); - distStatusSet.add(distEnum); - Either, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null); - if (servicesWithDistStatus.isRight()) { // not found == empty list - return Either.left(new ArrayList<>()); - } - - return Either.left((List)servicesWithDistStatus.left().value()); - } - - public Either, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) { - - if (assetType == null || assetType == null) { - log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); - - if (assetTypeEnum == null) { - log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - Map additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - - switch (assetTypeEnum) { - case RESOURCE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - Either, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); - if(componentsListByUuid.isRight()) { - log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue()+ " fetching failed"); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum); - return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid)); - } - - log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful"); - return Either.left(componentsListByUuid.left().value()); - } - - public List getAllComponentTypesParamNames() { - List paramNames = new ArrayList<>(); - paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME); - paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME); - paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME); - return paramNames; - } - - public List getAllSupportedRoles() { - Role[] values = Role.values(); - List roleNames = new ArrayList<>(); - for (Role role : values) { - roleNames.add(role.name()); - } - return roleNames; - } - - public Either, ActionStatus> getResourceTypesMap() { - return elementOperation.getResourceTypesMap(); - } - - private Optional findInvalidFilter(String query, ComponentTypeEnum assetType) { - List params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8); - List validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType); - Predicate noMatch = p -> !validKeys.contains(p.getName()); - return params.stream().filter(noMatch).findAny(); - } - - private List getErrorResponseParams(Map filters, ComponentTypeEnum assetType) { - List params = new ArrayList(); - if (1 == filters.size()) { - params.add(assetType.getValue().toLowerCase()); - params.add(filters.keySet().iterator().next().getName()); - params.add(filters.values().iterator().next()); - } else { - params.add(assetType.getValue()); - params.add(filters.get(FilterKeyEnum.SUB_CATEGORY)); - params.add(filters.get(FilterKeyEnum.CATEGORY)); - } - return params; - } - - public Either, StorageOperationStatus> getFilteredResouces(Map filters, boolean inTransaction) { - - String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); - String categoryName = filters.get(FilterKeyEnum.CATEGORY); - ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE)); - Either>, StorageOperationStatus> subcategories = null; - Optional> subCategoryData; - - if (categoryName != null) { - subcategories = getAllSubCategories(categoryName); - if (subcategories.isRight()) { - filters.remove(FilterKeyEnum.SUB_CATEGORY); - return Either.right(subcategories.right().value()); - } - } - if (subCategoryName != null) { // primary filter - if (categoryName != null) { - subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); - if (!subCategoryData.isPresent()) { - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, - ResourceMetadataData.class, resourceType); - } - - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); - } - if(subcategories != null){ - return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); - } - return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction); - } - - private Either>, StorageOperationStatus> getAllSubCategories(String categoryName) { - Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); - if (categoryResult.isRight()) { - return Either.right(categoryResult.right().value()); - } - CategoryData categoryData = categoryResult.left().value(); - - Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); - if (childrenNodes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); - } - return Either.left(childrenNodes.left().value()); - } - - private Optional> validateCategoryHierarcy(List> childNodes, String subCategoryName) { - Predicate> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); - return childNodes.stream().filter(matchName).findAny(); - } - - protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class clazz, ResourceTypeEnum resourceType) { - try { - Either graph = titanDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType); - - } finally { - if (false == inTransaction) { - titanDao.commit(); - } - } - } - - protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class clazz, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - try { - Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); - Either, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); - if (getCategory.isRight()) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - Either graph = titanDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - - } - for (GraphNode category : getCategory.left().value()) { - Either, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); - if (result.isRight()) { - return result; - } - components.addAll(result.left().value()); - } - - return Either.left(components); - } finally { - if (false == inTransaction) { - titanDao.commit(); - } - } - } - - private Either, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class clazz, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - Either>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); - if (parentNodes.isLeft()) { - for (ImmutablePair component : parentNodes.left().value()) { - ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); - Boolean isHighest = componentData.isHighestVersion(); - boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); - - if (isHighest && isMatchingResourceType) { - Either result = (Either) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (result.isRight()) { - return Either.right(result.right().value()); - } - components.add(result.left().value()); - } - } - } - return Either.left(components); - } - - private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, - ComponentMetadataDataDefinition componentData) { - - boolean isMatching; - if (componentType == NodeTypeEnum.Resource) { - if (resourceType == null) { - isMatching = true; - } else { - isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType(); - } - } else { - isMatching = true; - } - return isMatching; - } - - private Either, StorageOperationStatus> fetchByMainCategory(List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { - List components = new ArrayList<>(); - - for (ImmutablePair subCategory : subcategories) { - Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, - inTransaction, ResourceMetadataData.class, resourceType); - if (fetched.isRight()) { - // return fetched; - continue; - } - components.addAll(fetched.left().value()); - } - return Either.left(components); - } - - private Either, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) { - List components = null; - StorageOperationStatus status; - Wrapper statusWrapper = new Wrapper<>(); - Either, StorageOperationStatus> result; - try { - ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue())); - Either, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter); - if (getResources.isRight()) { - status = getResources.right().value(); - if(status != StorageOperationStatus.NOT_FOUND){ - statusWrapper.setInnerElement(getResources.right().value()); - }else{ - components = new ArrayList<>(); - } - } else{ - components = getResources.left().value(); - } - if(!statusWrapper.isEmpty()){ - result = Either.right(statusWrapper.getInnerElement()); - }else{ - result = Either.left(components); - } - return result; - } finally { - if (!inTransaction) { - titanDao.commit(); - } - } - } - - Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) { - return convertResourceDataToResource((ResourceMetadataData) componentMetadataData); - } - private Resource convertResourceDataToResource(ResourceMetadataData resourceData) { - - ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()); - - Resource resource = new Resource(resourceMetadataDataDefinition); - - return resource; - } - private Either, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) { - Map props = new HashMap(); - props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status); - props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - return (Either, StorageOperationStatus>) (Either) getServiceListByCriteria(props, inTransaction); - } - - private Either, StorageOperationStatus> getServiceListByCriteria(Map props, boolean inTransaction) { - props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); - Either, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); - - if (byCriteria.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List services = new ArrayList(); - List servicesDataList = byCriteria.left().value(); - for (ServiceMetadataData data : servicesDataList) { - Either service = toscaOperationFacade.getToscaElement(data.getMetadataDataDefinition().getUniqueId()); - if (service.isLeft()) { - services.add((Service)service.left().value()); - } else { - log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId()); - } - } - return Either.left(services); - } - + private static final Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class); + + @javax.annotation.Resource + private IElementOperation elementOperation; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private UserBusinessLogic userAdminManager; + + /** + * + * @param user + * @return + */ + public Either>, ResponseFormat> getFollowed(User user) { + // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains + Either>, ResponseFormat> response = null; + // Getting the role + String role = user.getRole(); + String userId = null; + Role currentRole = Role.valueOf(role); + + switch (currentRole) { + case DESIGNER: + userId = user.getUserId(); + response = handleDesigner(userId); + break; + + case TESTER: + userId = user.getUserId(); + response = handleTester(userId); + break; + + case GOVERNOR: + userId = user.getUserId(); + response = handleGovernor(userId); + break; + + case OPS: + userId = user.getUserId(); + response = handleOps(userId); + break; + + case PRODUCT_STRATEGIST: + userId = user.getUserId(); + response = handleProductStrategist(userId); + break; + + case PRODUCT_MANAGER: + userId = user.getUserId(); + response = handleProductManager(userId); + break; + + case ADMIN: + response = handleAdmin(); + break; + + default: + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + break; + } + // converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice) + return convertedToListResponse(response); + + } + + private Either>, ResponseFormat> convertedToListResponse(Either>, ResponseFormat> setResponse) { + + Map> arrayResponse = new HashMap<>(); + if (setResponse.isLeft()) { + for (Map.Entry> entry : setResponse.left().value().entrySet()) { + arrayResponse.put(entry.getKey(), new ArrayList(new HashSet(entry.getValue()))); + } + return Either.left(arrayResponse); + } + return Either.right(setResponse.right().value()); + } + + private Either>, ResponseFormat> handleAdmin() { + Either>, ResponseFormat> response; + // userId should stay null + Set lifecycleStates = new HashSet(); + Set lastStateStates = new HashSet(); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates); + return response; + } + + private Either>, ResponseFormat> handleDesigner(String userId) { + Set lifecycleStates = new HashSet(); + Set lastStateStates = new HashSet(); + Either>, ResponseFormat> response; + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + // more states + lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates); + return response; + } + + private Either>, ResponseFormat> handleGovernor(String userId) { + Either>, ResponseFormat> result = handleFollowedCertifiedServices(null); + return result; + } + + private Either>, ResponseFormat> handleProductStrategist(String userId) { + // Should be empty list according to Ella, 13/03/16 + Map> result = new HashMap>(); + result.put("products", new HashSet<>()); + return Either.left(result); + } + + private Either>, ResponseFormat> handleProductManager(String userId) { + Set lifecycleStates = new HashSet(); + Set lastStateStates = new HashSet(); + Either>, ResponseFormat> response; + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.CERTIFIED); + // more states + lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + response = getFollowedProducts(userId, lifecycleStates, lastStateStates); + return response; + } + + private Either>, ResponseFormat> handleOps(String userId) { + Set distStatus = new HashSet(); + distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED); + distStatus.add(DistributionStatusEnum.DISTRIBUTED); + + Either>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus); + return result; + } + + private Either>, ResponseFormat> handleFollowedCertifiedServices(Set distStatus) { + + Either, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus); + if (services.isLeft()) { + Map> result = new HashMap<>(); + Set set = new HashSet<>(); + set.addAll(services.left().value()); + result.put("services", set); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + } + } + + private Either>, ResponseFormat> handleTester(String userId) { + Set lifecycleStates = new HashSet(); + lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null); + + return result; + } + + private Either>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set lifecycleStates, Set lastStateStates) { + + try { + Either, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE); + + if (resources.isLeft()) { + Either, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE); + if (services.isLeft()) { + Map> result = new HashMap>(); + result.put("services", services.left().value()); + result.put("resources", resources.left().value()); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value()))); + } + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value()))); + } + } finally { + titanDao.commit(); + } + } + + private Either>, ResponseFormat> getFollowedProducts(String userId, Set lifecycleStates, Set lastStateStates) { + Either, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT); + if (products.isLeft()) { + Map> result = new HashMap<>(); + result.put("products", products.left().value()); + return Either.left(result); + } else { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value()))); + } + } + + /* + * New categories flow - start + */ + public Either, ActionStatus> getAllResourceCategories() { + return elementOperation.getAllResourceCategories(); + } + + public Either, ActionStatus> getAllServiceCategories() { + return elementOperation.getAllServiceCategories(); + } + + public Either createCategory(CategoryDefinition category, String componentTypeParamName, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY; + + User user = new User(); + Either validateUser = validateUser(userId); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + String currCategoryName = (category == null ? null : category.getName()); + handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (category == null) { + log.debug("Category json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String categoryName = category.getName(); + // For auditing of failures we need the original non-normalized name + String origCategoryName = categoryName; + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) { + log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) { + log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + category.setName(categoryName); + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); + category.setNormalizedName(normalizedName); + + NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType); + + Either categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName); + if (categoryUniqueEither.isRight()) { + log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value()); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isCategoryUnique = categoryUniqueEither.left().value(); + if (!isCategoryUnique) { + log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either createCategoryByType = elementOperation.createCategory(category, nodeType); + if (createCategoryByType.isRight()) { + log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName); + handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType); + return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value())); + } + category = createCategoryByType.left().value(); + log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType); + return Either.left(category); + } + + public Either createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY; + // For auditing + String parentCategoryName = parentCategoryId; + + if (subCategory == null) { + log.debug("Sub-category json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String subCategoryName = subCategory.getName(); + // For auditing of failures we need the original non-normalized name + String origSubCategoryName = subCategoryName; + + User user = new User(); + Either validateUser = validateUserExists(userId, "createSubCategory", false); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); + if (validateComponentType.isRight()) { + log.debug("Validation of component type for sub-category failed"); + ResponseFormat responseFormat = validateComponentType.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + + CategoryDefinition categoryDefinition; + Either validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum); + if (validateCategoryExists.isRight()) { + log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId); + ResponseFormat responseFormat = validateCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryDefinition = validateCategoryExists.left().value(); + parentCategoryName = categoryDefinition.getName(); + + if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) { + log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) { + log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName); + subCategory.setNormalizedName(normalizedName); + + // Uniqueness under this category + Either subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId); + if (subCategoryUniqueForCategory.isRight()) { + log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isSubUnique = subCategoryUniqueForCategory.left().value(); + if (!isSubUnique) { + log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + // Setting name of subcategory to fit the similar subcategory name + // ignoring cases. + // For example if Network-->kUKU exists for service category Network, + // and user is trying to create Router-->Kuku for service category + // Router, + // his subcategory name will be Router-->kUKU. + Either subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName); + if (subCategoryUniqueForType.isRight()) { + log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value(); + if (subCategoryDefinition != null) { + subCategoryName = subCategoryDefinition.getName(); + } + + subCategory.setName(subCategoryName); + ///////////////////////////////////////////// Validations end + + Either createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType); + if (createSubCategory.isRight()) { + log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType); + return Either.right(responseFormat); + } + + SubCategoryDefinition subCategoryCreated = createSubCategory.left().value(); + log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType); + return Either.left(subCategoryCreated); + } + + public Either createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) { + + AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING; + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue(); + CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING; + // For auditing + String parentCategoryName = grandParentCategoryId; + String parentSubCategoryName = parentSubCategoryId; + + User user; + Either validateUser = validateUserExists(userId, "create Grouping", false); + if (validateUser.isRight()) { + log.debug("Validation of user failed, userId {}", userId); + ResponseFormat responseFormat = validateUser.right().value(); + user = new User(); + user.setUserId(userId); + String groupingNameForAudit = grouping == null ? null : grouping.getName(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType); + return Either.right(responseFormat); + } + + user = validateUser.left().value(); + + if (grouping == null) { + log.debug("Grouping json is invalid"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType); + return Either.right(responseFormat); + } + + String groupingName = grouping.getName(); + // For auditing of failures we need the original non-normalized name + String origGroupingName = groupingName; + + if (componentTypeEnum == null) { + log.debug("Component type {} is invalid", componentTypeParamName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType); + if (validateComponentType.isRight()) { + log.debug("Validation of component type for grouping failed"); + ResponseFormat responseFormat = validateComponentType.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Either validateUserRole = validateUserRole(user, componentTypeEnum); + if (validateUserRole.isRight()) { + log.debug("Validation of user role failed, userId {}", userId); + ResponseFormat responseFormat = validateUserRole.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); + + // Validate category + CategoryDefinition categoryDefinition; + Either validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum); + if (validateCategoryExists.isRight()) { + log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId); + ResponseFormat responseFormat = validateCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + categoryDefinition = validateCategoryExists.left().value(); + parentCategoryName = categoryDefinition.getName(); + + // Validate subcategory + SubCategoryDefinition subCategoryDefinition; + Either validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum); + if (validateSubCategoryExists.isRight()) { + log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId); + ResponseFormat responseFormat = validateSubCategoryExists.right().value(); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + subCategoryDefinition = validateSubCategoryExists.left().value(); + parentSubCategoryName = subCategoryDefinition.getName(); + + if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) { + log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName); + + if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) { + log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName); + grouping.setNormalizedName(normalizedName); + + // Uniqueness under this category + Either groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId); + if (groupingUniqueForSubCategory.isRight()) { + log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value(); + if (!isGroupingUnique) { + log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + // Setting name of grouping to fit the similar grouping name ignoring + // cases. + // For example if Network-->kUKU exists for service sub-category + // Network, and user is trying to create grouping Router-->Kuku for + // service sub-category Router, + // his grouping name will be Router-->kUKU. + Either groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName); + if (groupingUniqueForType.isRight()) { + log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + GroupingDefinition groupingDefinition = groupingUniqueForType.left().value(); + if (groupingDefinition != null) { + groupingName = groupingDefinition.getName(); + } + + grouping.setName(groupingName); + ///////////////////////////////////////////// Validations end + + Either createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType); + if (createGrouping.isRight()) { + log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value()); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType); + return Either.right(responseFormat); + } + + GroupingDefinition groupingCreated = createGrouping.left().value(); + log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType); + return Either.left(groupingCreated); + } + + public Either, ResponseFormat> getAllCategories(String componentType, String userId) { + AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; + ResponseFormat responseFormat; + User user = new User(); + if (userId == null) { + user.setUserId("UNKNOWN"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + + Either validateUser = validateUserExists(userId, "get All Categories", false); + if (validateUser.isRight()) { + user.setUserId(userId); + log.debug("Validation of user failed, userId {}", userId); + responseFormat = validateUser.right().value(); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + user = validateUser.left().value(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum == null) { + log.debug("Cannot create category for component type {}", componentType); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type"); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + Either, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false); + if (getAllCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.right(responseFormat); + } + List categories = getAllCategoriesByType.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat); + return Either.left(categories); + } + + public Either getAllCategories(String userId) { + AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY; + ResponseFormat responseFormat; + UiCategories categories = new UiCategories(); + + Either userResponse = validateUserExists(userId, "get all categories", false); + + if (userResponse.isRight()) { + return Either.right(userResponse.right().value()); + } + User user = userResponse.left().value(); + + // GET resource categories + Either, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false); + if (getResourceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setResourceCategories(getResourceCategoriesByType.left().value()); + + // GET service categories + Either, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false); + if (getServiceCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat); + return Either.right(responseFormat); + } + categories.setServiceCategories(getServiceCategoriesByType.left().value()); + + // GET product categories + Either, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false); + if (getProductCategoriesByType.isRight()) { + responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value()); + componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat); + return Either.right(responseFormat); + } + + categories.setProductCategories(getProductCategoriesByType.left().value()); + return Either.left(categories); + + } + + public Either deleteCategory(String categoryId, String componentTypeParamName, String userId) { + + Either resp = validateUserExists(userId, "delete Category", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot create category for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY); + + Either deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId); + if (deleteCategoryByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value())); + } + CategoryDefinition category = deleteCategoryByType.left().value(); + log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId()); + return Either.left(category); + } + + public Either deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) { + + Either resp = validateUserExists(userId, "delete Sub Category", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot delete sub-category for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY); + + Either deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId); + if (deleteSubCategoryByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value())); + } + SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value(); + log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId()); + return Either.left(subCategory); + } + + public Either deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) { + + Either resp = validateUserExists(userId, "delete Grouping", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName); + if (componentTypeEnum == null) { + log.debug("Cannot delete grouping for component type {}", componentTypeParamName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING); + + Either deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId); + if (deleteGroupingByType.isRight()) { + // auditing, logging here... + return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value())); + } + GroupingDefinition deletedGrouping = deleteGroupingByType.left().value(); + log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId()); + return Either.left(deletedGrouping); + } + + private Either validateUser(String userId) { + + // validate user exists + if (userId == null) { + log.debug("UserId is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION)); + } + + Either userResult = userAdminManager.getUser(userId, false); + if (userResult.isRight()) { + ResponseFormat responseFormat; + if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("Not authorized user, userId = {}", userId); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } else { + log.debug("Failed to authorize user, userId = {}", userId); + responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); + } + + return Either.right(responseFormat); + } + return Either.left(userResult.left().value()); + // ========================================- + } + + private Either validateUserRole(User user, ComponentTypeEnum componentTypeEnum) { + String role = user.getRole(); + boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE); + boolean validProductAction = role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT); + + if (!(validAdminAction || validProductAction)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) { + boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY); + boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY; + boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can + // be + // any + // category + // type + + if (!(validResourceAction || validServiceAction || validProductAction)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType); + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) { + Either categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId); + if (categoryByTypeAndId.isRight()) { + log.debug("Failed to fetch parent category, parent categoryId {}", categoryId); + ActionStatus actionStatus = categoryByTypeAndId.right().value(); + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), ""); + } else { + responseFormat = componentsUtils.getResponseFormat(actionStatus); + } + return Either.right(responseFormat); + } + return Either.left(categoryByTypeAndId.left().value()); + } + + private Either validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) { + Either subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId); + if (subCategoryByTypeAndId.isRight()) { + log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId); + ActionStatus actionStatus = subCategoryByTypeAndId.right().value(); + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) { + responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), ""); + } else { + responseFormat = componentsUtils.getResponseFormat(actionStatus); + } + return Either.right(responseFormat); + } + return Either.left(subCategoryByTypeAndId.left().value()); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType); + } + + private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) { + componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType); + } + + /* + * New categories flow - end + */ + + public Either, ActionStatus> getAllTags(String userId) { + Either resp = validateUserExistsActionStatus(userId, "get All Tags"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllTags(); + } + + public Either, ActionStatus> getAllPropertyScopes(String userId) { + Either resp = validateUserExistsActionStatus(userId, "get All Property Scopes"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllPropertyScopes(); + } + + public Either, ActionStatus> getAllArtifactTypes(String userId) { + Either resp = validateUserExistsActionStatus(userId, "get All Artifact Types"); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return elementOperation.getAllArtifactTypes(); + } + + public Either, ActionStatus> getAllDeploymentArtifactTypes() { + return elementOperation.getAllDeploymentArtifactTypes(); + } + + public Either getDefaultHeatTimeout() { + return elementOperation.getDefaultHeatTimeout(); + } + + public Either>, ResponseFormat> getCatalogComponents(String userId) { + try { + Either resp = validateUserExists(userId, "get Catalog Components", true); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + return toscaOperationFacade.getCatalogComponents().bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err))); + } finally { + titanDao.commit(); + } + } + + private Map> groupByComponentType(List components) { + Map> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType()))); + + // fixed response for UI!!! UI need to receive always map! + if (map == null) { + map = new HashMap<>(); + } + if (map.get("resources") == null) { + map.put("resources", new ArrayList()); + } + if (map.get("services") == null) { + map.put("services", new ArrayList()); + } + return map; + } + + private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) { + switch (componentTypeEnum) { + case RESOURCE: + return "resources"; + case SERVICE: + return "services"; + default: + throw new IllegalStateException("resources or services only"); + } + } + + public Either, ResponseFormat> getFilteredCatalogComponents(String assetType, Map filters, String query) { + ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); + + if (query != null) { + Optional invalidFilter = findInvalidFilter(query, assetTypeEnum); + if (invalidFilter.isPresent()) { + log.debug("getFilteredAssetList: invalid filter key"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString())); + } + } + + if (filters == null || filters.isEmpty()) { + Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, null, false); + if (componentsList.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); + } + return Either.left(componentsList.left().value()); + } + + Either, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false); + + // category hierarchy mismatch or category/subCategory/distributionStatus not found + if (result.isRight()) { + List params = getErrorResponseParams(filters, assetTypeEnum); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2))); + } + if (result.left().value().isEmpty()) {// no assets found for requested + // criteria + return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query)); + } + return Either.left(result.left().value()); + } + + private Either, StorageOperationStatus> getFilteredComponents(Map filters, ComponentTypeEnum assetType, boolean inTransaction) { + Either, StorageOperationStatus> assetResult = Either.left(new LinkedList<>()); + if (assetType == ComponentTypeEnum.RESOURCE) { + + assetResult = getFilteredResouces(filters, inTransaction); + + } else if (assetType == ComponentTypeEnum.SERVICE) { + + assetResult = getFilteredServices(filters, inTransaction); + } + return assetResult; + } + + private Either, StorageOperationStatus> getFilteredServices(Map filters, boolean inTransaction) { + + Either, StorageOperationStatus> components = null; + + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS); + DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus); + if (distributionStatus != null && distEnum == null) { + filters.remove(FilterKeyEnum.CATEGORY); + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + + if (categoryName != null) { // primary filter + components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); + if (components.isLeft() && distEnum != null) {// secondary filter + Predicate statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); + return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); + } + filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); + return components; + } + + Set distStatusSet = new HashSet<>(); + distStatusSet.add(distEnum); + Either, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null); + if (servicesWithDistStatus.isRight()) { // not found == empty list + return Either.left(new ArrayList<>()); + } + + return Either.left((List) servicesWithDistStatus.left().value()); + } + + public Either, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) { + + if (assetType == null || uuid == null) { + log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType); + + if (assetTypeEnum == null) { + log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + Map additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + + switch (assetTypeEnum) { + case RESOURCE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + Either, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch); + if (componentsListByUuid.isRight()) { + log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + " fetching failed"); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum); + return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid)); + } + + log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful"); + return Either.left(componentsListByUuid.left().value()); + } + + public List getAllComponentTypesParamNames() { + List paramNames = new ArrayList<>(); + paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME); + paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME); + paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME); + return paramNames; + } + + public List getAllSupportedRoles() { + Role[] values = Role.values(); + List roleNames = new ArrayList<>(); + for (Role role : values) { + roleNames.add(role.name()); + } + return roleNames; + } + + public Either, ActionStatus> getResourceTypesMap() { + return elementOperation.getResourceTypesMap(); + } + + private Optional findInvalidFilter(String query, ComponentTypeEnum assetType) { + List params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8); + List validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType); + Predicate noMatch = p -> !validKeys.contains(p.getName()); + return params.stream().filter(noMatch).findAny(); + } + + private List getErrorResponseParams(Map filters, ComponentTypeEnum assetType) { + List params = new ArrayList(); + if (1 == filters.size()) { + params.add(assetType.getValue().toLowerCase()); + params.add(filters.keySet().iterator().next().getName()); + params.add(filters.values().iterator().next()); + } else { + params.add(assetType.getValue()); + params.add(filters.get(FilterKeyEnum.SUB_CATEGORY)); + params.add(filters.get(FilterKeyEnum.CATEGORY)); + } + return params; + } + + public Either, StorageOperationStatus> getFilteredResouces(Map filters, boolean inTransaction) { + + String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); + String categoryName = filters.get(FilterKeyEnum.CATEGORY); + ResourceTypeEnum resourceType = ResourceTypeEnum.getType(filters.get(FilterKeyEnum.RESOURCE_TYPE)); + Either>, StorageOperationStatus> subcategories = null; + Optional> subCategoryData; + + if (categoryName != null) { + subcategories = getAllSubCategories(categoryName); + if (subcategories.isRight()) { + filters.remove(FilterKeyEnum.SUB_CATEGORY); + return Either.right(subcategories.right().value()); + } + } + if (subCategoryName != null) { // primary filter + if (categoryName != null) { + subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName); + if (!subCategoryData.isPresent()) { + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, + ResourceMetadataData.class, resourceType); + } + + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); + } + if (subcategories != null) { + return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); + } + return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction); + } + + private Either>, StorageOperationStatus> getAllSubCategories(String categoryName) { + Either categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); + if (categoryResult.isRight()) { + return Either.right(categoryResult.right().value()); + } + CategoryData categoryData = categoryResult.left().value(); + + Either>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), + GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); + if (childrenNodes.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value())); + } + return Either.left(childrenNodes.left().value()); + } + + private Optional> validateCategoryHierarcy(List> childNodes, String subCategoryName) { + Predicate> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); + return childNodes.stream().filter(matchName).findAny(); + } + + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class clazz, ResourceTypeEnum resourceType) { + try { + return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType); + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + protected Either, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, + Class clazz, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + try { + Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; + Map props = new HashMap(); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + Either, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); + if (getCategory.isRight()) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + for (GraphNode category : getCategory.left().value()) { + Either, StorageOperationStatus> result = collectComponents(neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); + if (result.isRight()) { + return result; + } + components.addAll(result.left().value()); + } + + return Either.left(components); + } finally { + if (false == inTransaction) { + titanDao.commit(); + } + } + } + + private Either, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class clazz, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + Either>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); + if (parentNodes.isLeft()) { + for (ImmutablePair component : parentNodes.left().value()) { + ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); + Boolean isHighest = componentData.isHighestVersion(); + boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); + boolean isDeleted = componentData.isDeleted() != null && componentData.isDeleted(); + + if (isHighest && isMatchingResourceType && !isDeleted) { + Either result = (Either) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (result.isRight()) { + return Either.right(result.right().value()); + } + components.add(result.left().value()); + } + } + } + return Either.left(components); + } + + private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) { + + boolean isMatching; + if (componentType == NodeTypeEnum.Resource) { + if (resourceType == null) { + isMatching = true; + } else { + isMatching = resourceType == ((ResourceMetadataDataDefinition) componentData).getResourceType(); + } + } else { + isMatching = true; + } + return isMatching; + } + + private Either, StorageOperationStatus> fetchByMainCategory(List> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { + List components = new ArrayList<>(); + + for (ImmutablePair subCategory : subcategories) { + Either, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, + inTransaction, ResourceMetadataData.class, resourceType); + if (fetched.isRight()) { + continue; + } + components.addAll(fetched.left().value()); + } + return Either.left(components); + } + + private Either, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) { + List components = null; + StorageOperationStatus status; + Wrapper statusWrapper = new Wrapper<>(); + Either, StorageOperationStatus> result; + try { + ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue())); + Either, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter); + if (getResources.isRight()) { + status = getResources.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + statusWrapper.setInnerElement(getResources.right().value()); + } else { + components = new ArrayList<>(); + } + } else { + components = getResources.left().value(); + } + if (!statusWrapper.isEmpty()) { + result = Either.right(statusWrapper.getInnerElement()); + } else { + result = Either.left(components); + } + return result; + } finally { + if (!inTransaction) { + titanDao.commit(); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java new file mode 100644 index 0000000000..7233ba7657 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by yavivi on 04/02/2018. + */ +@org.springframework.stereotype.Component +public class ExternalRefsBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(ExternalRefsBusinessLogic.class); + + private ExternalReferencesOperation externalReferencesOperation; + private ToscaOperationFacade toscaOperationFacade; + private GraphLockOperation graphLockOperation; + + public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, GraphLockOperation graphLockOperation){ + this.externalReferencesOperation = externalReferencesOperation; + this.toscaOperationFacade = toscaOperationFacade; + this.graphLockOperation = graphLockOperation; + } + + public Either, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){ + Either componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version); + if (componentsResult == null || componentsResult.isRight()) { + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + Component component = componentsResult.left().value(); + return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType); + } + + public Either>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType){ + Either componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version); + if (componentsResult == null || componentsResult.isRight()) { + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + Component component = componentsResult.left().value(); + + Either>, ActionStatus> externalReferencesResult = this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), objectType); + if (externalReferencesResult.isRight()){ + return Either.right(externalReferencesResult.right().value()); + } else { + return Either.left(externalReferencesResult.left().value()); + } + } + + public Either addExternalReference(String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) { + return this.doAction("POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), ""); + } + + + public Either deleteExternalReference(String uuid, String componentInstanceName, String objectType, String reference) { + return this.doAction("DELETE", uuid, componentInstanceName, objectType, reference, ""); + } + + public Either updateExternalReference(String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) { + return this.doAction("PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue); + } + + private Either doAction(String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){ + Either latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch()); + if (latestServiceByUuid == null || latestServiceByUuid.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + //Get Component Unique ID + Component component = latestServiceByUuid.left().value(); + String uniqueId = component.getUniqueId(); + + //Lock Asset + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service); + if (lockStatus != StorageOperationStatus.OK){ + return Either.right(ActionStatus.GENERAL_ERROR); + } + + Either opResult = Either.right(ActionStatus.GENERAL_ERROR); + try { + switch (action) { + case "POST": + opResult = this.externalReferencesOperation.addExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); + break; + case "PUT": + opResult = this.externalReferencesOperation.updateExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1, ref2); + break; + case "DELETE": + opResult = this.externalReferencesOperation.deleteExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1); + break; + default: + break; + } + } catch (Exception e) { + opResult = Either.right(ActionStatus.GENERAL_ERROR); + log.error("Failed to execute external ref action:{} on asset:{} component:{} objectType:{}", action, uuid, componentInstanceName, objectType); + log.error("Cause is:" , e); + } finally { + //Unlock Asset + this.graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service); + } + return opResult; + } + + private Map createPropsToMatch() { + Map propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + return propertiesToMatch; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index de571b0f03..63b72b932e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -20,29 +20,20 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.utils.Utils; +import org.openecomp.sdc.be.components.validation.AccessValidations; +import org.openecomp.sdc.be.components.validation.ComponentValidations; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; @@ -69,2084 +60,1666 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; -import fj.data.Either; +import static java.util.stream.Collectors.toList; @org.springframework.stereotype.Component("groupBusinessLogic") public class GroupBusinessLogic extends BaseBusinessLogic { - private static String ADDING_GROUP = "AddingGroup"; - - public static final String INITIAL_VERSION = "1"; - - private static final String CREATE_GROUP = "CreateGroup"; - - private static final String UPDATE_GROUP = "UpdateGroup"; - - private static final String GET_GROUP = "GetGroup"; - - private static Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class.getName()); - - public GroupBusinessLogic() { - - } - - @javax.annotation.Resource - private GroupTypeOperation groupTypeOperation; - - @Autowired - ArtifactsOperations artifactsOperation; - - @Autowired - private GroupsOperation groupsOperation; - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - /** - * - * 1. validate user exist - * - * 2. validate component can be edited - * - * 3. verify group not already exist - * - * 4. verify type of group exist - * - * 5. verify Component instances exist under the component - * - * 6. verify the component instances type are allowed according to the member types in the group type - * - * 7. verify the artifacts belongs to the component - * - * @param componentId - * @param userId - * @param componentType - * @param groupDefinition - * @param inTransaction - * @return - */ - /* - * public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - * - * Either result = null; - * - * try { Either validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); - * - * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } - * - * User user = validateUserExists.left().value(); // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state org.openecomp.sdc.be.model.Component component = null; - * - * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId; - * - * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); - * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - * - * Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - * - * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either canWork = validateCanWorkOnComponent(component, - * userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } - * - * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } } - */ - - private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { - String componentTypeForResponse = "SERVICE"; - if (component instanceof Resource) { - componentTypeForResponse = ((Resource) component).getResourceType().name(); - } - return componentTypeForResponse; - } - - /** - * Verify that the artifact members belongs to the component - * - * @param component - * @param artifacts - * @return - */ - private Either verifyArtifactsBelongsToComponent(Component component, List artifacts, String context) { - - if (artifacts == null || true == artifacts.isEmpty()) { - return Either.left(true); - } - - Map deploymentArtifacts = component.getDeploymentArtifacts(); - if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - List currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); - if (false == currentArtifacts.containsAll(artifacts)) { - BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return Either.left(true); - - } - - /** - * verify that the members are component instances of the component - * - * @param component - * @param componentType - * @param groupMembers - * @param memberToscaTypes - * @return - */ - private Either verifyComponentInstancesAreValidMembers(Component component, ComponentTypeEnum componentType, String groupName, String groupType, Map groupMembers, List memberToscaTypes) { - - if (groupMembers == null || true == groupMembers.isEmpty()) { - return Either.left(true); - } - - if (memberToscaTypes == null || true == memberToscaTypes.isEmpty()) { - return Either.left(true); - } - - List componentInstances = component.getComponentInstances(); - if (componentInstances != null && false == componentInstances.isEmpty()) { - Map compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); - - Set allCompInstances = compInstUidToCompInstMap.keySet(); - - for (Entry groupMember : groupMembers.entrySet()) { - String compName = groupMember.getKey(); - String compUid = groupMember.getValue(); - - if (false == allCompInstances.contains(compUid)) { - /* - * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ] - */ - String componentTypeForResponse = getComponentTypeForResponse(component); - - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse)); - } - } - - // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); - // if (componentOperation instanceof ResourceOperation) { - // ResourceOperation resourceOperation = (ResourceOperation) componentOperation; - // - // for (Entry groupMember : groupMembers.entrySet()) { - // - // String componentInstName = groupMember.getKey(); - // String componentInstUid = groupMember.getValue(); - // - // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); - // String componentUid = componentInstance.getComponentUid(); - // List componentToscaNames = new ArrayList<>(); - // TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); - // if (status != TitanOperationStatus.OK) { - // BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - // } - // - // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); - // - // boolean found = false; - // for (String memberToscaType : memberToscaTypes) { - // if (componentToscaNames.contains(memberToscaType)) { - // found = true; - // break; - // } - // } - // if (found == false) { - // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, - // "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); - // /* - // * # %1 - member name # %2 - group name # %3 - group type - // */ - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); - // } else { - // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); - // } - // } - // } else { - // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); - // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - // } - - } - - return Either.left(true); - } - - /** - * Update specific group version - * - * @param groupDefinition - * @param inTransaction - * @return - */ - /* - * public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either result = null; List groupIdsToUpdateVersion = new - * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); if (updateGroupVersion.isLeft()) - * { result = Either.left(updateGroupVersion.left().value().get(0)); } else { log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); result = Either.right(updateGroupVersion.right().value()); } return - * result; } - */ - - /** - * Update list of groups versions - * - * @param groupsUniqueId - * @param inTransaction - * @return - */ - /* - * public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { - * - * Either, StorageOperationStatus> result = null; - * - * try { - * - * result = groupOperation.updateGroupVersion(groupsUniqueId, true); - * - * return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - */ - - /** - * Update GroupDefinition metadata - * - * @param componentId - * @param user - * @param componentType - * @param updatedGroup - * @param inTransaction - * @return - */ - public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { - - Either result = null; - try { - // Validate user exist - Either validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - // Validate component exist - Either validateComponent = validateComponentExists(componentId, componentType, null); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); - // validate we can work on component - Either canWork = validateCanWorkOnComponent(component, user.getUserId()); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - List currentGroups = component.getGroups(); - if (CollectionUtils.isEmpty(currentGroups)) { - log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); - return result; - } - // Validate groups exists in the component - Optional currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); - if (!currentGroupOpt.isPresent()) { - log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); - return result; - } - GroupDefinition currentGroup = currentGroupOpt.get(); - if ( shouldLock ){ - Either lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); - if (lockResult.isRight()) { - result = Either.right(lockResult.right().value()); - return result; - } - } - // Validate group type is vfModule - if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType()); - result = Either.right(responseFormat); - return result; - } - result = updateGroupMetadata(component, currentGroup, updatedGroup); - return result; - - } finally { - if (result.isLeft()) { - titanDao.commit(); - } else { - titanDao.rollback(); - } - if( shouldLock ) - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - } - - private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { - String currentGroupName = currentGroup.getName(); - Either result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); - - if (result.isRight()) { - log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); - } - if (result.isLeft()) { - result = updateGroup(component, currentGroup, currentGroupName); - } - return result; - } - - private Either updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { - Either handleGroupRes; - Either result = null; - if (updatedGroup.getName().equals(currentGroupName)) { - handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } - } else { - StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); - if (deleteStatus != StorageOperationStatus.OK) { - log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); - } - handleGroupRes = groupsOperation.addGroup(component, updatedGroup); - if (handleGroupRes.isRight()) { - log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); - } - } - if (result == null) { - result = Either.left(updatedGroup); - } - return result; - } - - /** - * Validate and Update Group Property - * - * @param componentId - * @param groupUniqueId - * @param user - * @param componentType - * @param groupPropertiesToUpdate - * @param inTransaction - * @return - */ - public Either, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List groupPropertiesToUpdate, boolean inTransaction) { - - Either, ResponseFormat> result = Either.left(groupPropertiesToUpdate); - try { - Optional optionalGroupConnectedToVf = null; - GroupDefinition currentGroup = null; - StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); - if (lockResult != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); - } - if (result.isLeft()) { - // VF exist because lock succedded - Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); - optionalGroupConnectedToVf = - // All groups on resource - vf.getGroups().stream(). - // Filter in group sent is part of VF groups - filter(e -> e.getUniqueId().equals(groupUniqueId)). - // Collect - findAny(); - if (!optionalGroupConnectedToVf.isPresent()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); - } - } - - if (result.isLeft()) { - currentGroup = optionalGroupConnectedToVf.get(); - result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); - } - if (result.isLeft()) { - result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); - if (result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); - log.debug("failed to update Vf {}", componentId); - } - } - - } catch (Exception e) { - log.debug("Error in validateAndUpdateGroupProperty {}", e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - return result; - } - - private void resetEmptyValueWithDefaults(List groupPropertiesToUpdate, GroupDefinition originalGroup) { - Map originalProperties = - // Stream of original properties from group - originalGroup.convertToGroupProperties().stream(). - // Collecting to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - for (GroupProperty gp : groupPropertiesToUpdate) { - if (StringUtils.isEmpty(gp.getValue())) { - gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); - } - } - - } - - private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List groupPropertiesToUpdate) { - - Either, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); - if (ret.isLeft()) { - resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); - } - if (ret.isLeft()) { - // Validate Type Match Value - Optional optionalError = - // Stream of group properties - groupPropertiesToUpdate.stream(). - // Validate each and map to returned Strorage status value - map(e -> groupOperation.validateAndUpdatePropertyValue(e)). - // Keep only failed result if there is such - filter(e -> e != StorageOperationStatus.OK). - // collect - findFirst(); - if (optionalError.isPresent()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); - ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - } - if (ret.isLeft()) { - // Validate min max ect... - ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); - } - - return ret; - } - - private Either, ResponseFormat> validatePropertyBusinessLogic(List groupPropertiesToUpdate, GroupDefinition originalGroup) { - - Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - - Map nameValueMap = new HashMap<>(); - for (GroupProperty gp : groupPropertiesToUpdate) { - // Filter out non special properties which does not have Enum - final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); - if (gpEnum != null) { - nameValueMap.put(gpEnum, gp.getValue()); - } - } - - if (!MapUtils.isEmpty(nameValueMap)) { - - if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { - - Map oldValueMap = prepareMapWithOriginalProperties(originalGroup); - - Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); - if (eitherValid.isRight()) { - ret = Either.right(eitherValid.right().value()); - } - } - if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { - - Optional optionalError = - // Stream of group Properties - groupPropertiesToUpdate.stream(). - // Filter in only properties that needs text validation - filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). - // validate text properties - map(e -> validateFreeText(e)). - // filter in only errors if exist - filter(e -> e.isRight()). - // map the Either value to the Error - map(e -> e.right().value()) - // collect - .findFirst(); - if (optionalError.isPresent()) { - ret = Either.right(optionalError.get()); - } - - } - } - - return ret; - } - - private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { - Map oldValueMap = new HashMap<>(); - PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; - - for (GroupProperty gp : originalGroup.convertToGroupProperties()) { - if (enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)) { - oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); - } - } - if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { - oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); - } - return oldValueMap; - } - - private Either, ResponseFormat> validateOnlyValueChanged(List groupPropertiesToUpdate, GroupDefinition originalGroup) { - - Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); - } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); - } else { - Map namePropertyMap = - // Original Group Properties Stream - originalGroup.convertToGroupProperties().stream(). - // Collect to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - - Optional optionalMissingProperty = - // Group Properties to be updated Stream - groupPropertiesToUpdate.stream(). - // Filter in property that is not contained in original if there is such - filter(e -> !namePropertyMap.containsKey(e.getName())). - // collect - findFirst(); - - if (optionalMissingProperty.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); - } else { - Optional optionalNonValueChange = - // groups to be updated stream - groupPropertiesToUpdate.stream(). - // filter in only properties with non-value (illegal) change - filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). - // Collect - findFirst(); - if (optionalNonValueChange.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); - - } - } - - } - return ret; - } - - /** - * if groupProperty are the same or if only value is different returns true, otherwise returns false. - * - * @param groupProperty - * @param groupProperty2 - * @return - */ - private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { - // Create 2 duplicates for groupPropery and reset their values - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - try { - GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); - groupPropertyDuplicate.setValue(null); - groupPropertyDuplicate.setSchema(null); - groupPropertyDuplicate.setParentUniqueId(null); - // GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); - GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); - groupProperty2Duplicate.setValue(null); - groupProperty2Duplicate.setSchema(null); - groupProperty2Duplicate.setParentUniqueId(null); - return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()); - } catch (Exception e) { - log.debug("Failed validate group properties. ", e); - return false; - } - } - - /** - * Validate and update GroupDefinition metadata - * - * @param user - * @param currentGroup - * @param groupUpdate - * @return - **/ - private Either validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) { - // Check if to update, and update GroupDefinition name. - Either response = validateAndUpdateGroupName(currentGroup, groupUpdate); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - // Do not allow to update GroupDefinition version directly. - String versionUpdated = groupUpdate.getVersion(); - String versionCurrent = currentGroup.getVersion(); - if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { - log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); - } - - return Either.left(currentGroup); - } - - /** - * Validate and update GroupDefinition name - * - * @param user - * @param currentGroup - * @param groupUpdate - * @return - */ - private Either validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) { - String nameUpdated = groupUpdate.getName(); - String nameCurrent = currentGroup.getName(); - if (!nameCurrent.equals(nameUpdated)) { - Either validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true); - if (validatNameResponse.isRight()) { - ResponseFormat errorRespons = validatNameResponse.right().value(); - return Either.right(errorRespons); - } - currentGroup.setName(groupUpdate.getName()); - } - return Either.left(true); - } - - /** - * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part - * MyDesc was changed. - * - * @param currentGroupName - * @param groupUpdateName - * @return - */ - private Either validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) { - try { - // Check if the group name is in old format. - if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) { - log.error("Group name {} is in old format", groupUpdateName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName)); - } - - // Check that name pats 1 and 3 did not changed (only the second - // part can be changed) - // But verify before that the current group format is the new one - if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) { - String[] split1 = currentGroupName.split("\\.\\."); - String currentResourceName = split1[0]; - String currentCounter = split1[2]; - - String[] split2 = groupUpdateName.split("\\.\\."); - String groupUpdateResourceName = split2[0]; - String groupUpdateCounter = split2[2]; - if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes] - if (!currentResourceName.equals(groupUpdateResourceName)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName)); - } - - if (!currentCounter.equals(groupUpdateCounter)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter)); - } - } - - } - - return Either.left(true); - } catch (Exception e) { - log.error("Error valiadting group name", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - - /** - * associate artifacts to a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /* - * public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List updatedGroups = new ArrayList<>(); - * - * List componentGroups = component.getGroups(); - * - * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { - * - * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = - * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List artifactsToAssociate = groupDefinition.getArtifacts(); - * - * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; } - * - * boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group log.debug("Some of the artifacts already associated to group {}" , - * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } } - * - * Either associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - * - * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } } - */ - - /* - * public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List updatedGroups = new ArrayList<>(); - * - * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) { - * - * Either associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); - * - * if (associateMembersToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } else { updatedGroups.add(associateMembersToGroup.left().value()); } - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } } - */ - - /** - * associate artifacts to a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - public Either getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) { - - Either result = null; - - // Validate user exist - Either validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - org.openecomp.sdc.be.model.Component component = null; - String realComponentId = componentId; - - try { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - Either groupEither = findGroupOnComponent(component, groupId); - - if (groupEither.isRight()) { - log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); - return result; - } - GroupDefinition group = groupEither.left().value(); - - Boolean isBase = null;// Constants.IS_BASE; - List props = group.convertToGroupProperties(); - if (props != null && !props.isEmpty()) { - Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - // return - // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - - } - } - - List artifacts = new ArrayList<>(); - List artifactsFromComponent = new ArrayList<>(); - List artifactsIds = group.getArtifacts(); - - Map deploymentArtifacts = null; - if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { - deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); - } - - if (artifactsIds != null && !artifactsIds.isEmpty()) { - for (String id : artifactsIds) { - if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { - log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); - result = Either.right(responseFormat); - return result; - } - artifactsFromComponent.add(deploymentArtifacts.get(id)); - } - if (!artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); - } - } - - } - GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); - resultInfo.setIsBase(isBase); - if (!artifacts.isEmpty()) - resultInfo.setArtifacts(artifacts); - - result = Either.left(resultInfo); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - } - - private Either findGroupOnComponent(Component component, String groupId) { - - Either result = null; - if (CollectionUtils.isNotEmpty(component.getGroups())) { - Optional foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); - if (foundGroup.isPresent()) { - result = Either.left(foundGroup.get()); - } - } - if (result == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - return result; - } - - /** - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param inTransaction - * @return - */ - private Either validateGroupsBeforeUpdate(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean inTransaction) { - - Either result; - - // Validate user exist - Either validateUserExists = validateUserExists(userId, UPDATE_GROUP, inTransaction); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - String realComponentId = componentId; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); - - // validate we can work on component - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - // Validate groups exists in the component - ResponseFormat validateGroupsInComponent = validateGroupsInComponentByFunc(groups, component, p -> p.getUniqueId()); - if (validateGroupsInComponent != null) { - result = Either.right(validateGroupsInComponent); - return result; - } - - Set artifacts = new HashSet<>(); - groups.forEach(p -> { - if (p.getArtifacts() != null) { - artifacts.addAll(p.getArtifacts()); - } - }); - // validate all artifacts belongs to the component - Either verifyArtifactsBelongsToComponent = verifyArtifactsBelongsToComponent(component, new ArrayList<>(artifacts), UPDATE_GROUP); - if (verifyArtifactsBelongsToComponent.isRight()) { - result = Either.right(verifyArtifactsBelongsToComponent.right().value()); - return result; - } - - return Either.left(component); - } - - /** - * @param groups - * @param component - * @param getByParam - * - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component - * @return - */ - private ResponseFormat validateGroupsInComponentByFunc(List groups, org.openecomp.sdc.be.model.Component component, Function getByParam) { - ResponseFormat result = null; - - List currentGroups = component.getGroups(); - - boolean found = false; - List updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - - List missingGroupNames = updatedGroupsName; - - if (currentGroups != null && false == currentGroups.isEmpty()) { - List currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - - if (currentGroupsName.containsAll(updatedGroupsName)) { - found = true; - } else { - currentGroupsName.removeAll(currentGroupsName); - missingGroupNames = currentGroupsName; - } - } - if (false == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - String listOfGroups = getAsString(missingGroupNames); - result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); - return result; - } - - return null; - } - - public String getAsString(List list) { - - if (list == null || list.isEmpty()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - list.forEach(p -> builder.append(p + ",")); - - String result = builder.toString(); - return result.substring(0, result.length()); - - } - - /** - * dissociate artifacts from a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /* - * public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - * - * Either, ResponseFormat> result = null; - * - * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock - * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Component component = null; - * - * try { - * - * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } - * - * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = - * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } - * - * component = validateGroupsBeforeUpdate.left().value(); - * - * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * List updatedGroups = new ArrayList<>(); - * - * List componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { - * - * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = - * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List artifactsToDissociate = groupDefinition.getArtifacts(); - * - * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; } - * - * if (artifactsSizeInGroup > 0) { - * - * boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); if (false == containsAll) { // At least one artifact is // not associated to the // group log.debug("Some of the artifacts already dissociated to group {}" , - * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null && - * false == artifactsToDissociate.isEmpty()) { log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, - * componentGroup.getName())); } } } } - * - * Either associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - * - * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); - * - * } - * - * result = Either.left(updatedGroups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } - * - * } - */ - - /* - * public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { - * - * Either, ResponseFormat> result = null; - * - * List groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try { - * - * if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - * - * if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of - * another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } - * - * Either validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } - * - * User user = validateUserExists.left().value(); - * - * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); - * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); - * - * Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - * - * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); - * - * if (shouldLockComp) { Either lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } - * - * Either canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } - * - * for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) { - * log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } GroupDefinition createdGroup = createGroup.left().value(); groups.add(createdGroup); } } - * - * result = Either.left(groups); return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } - * - * } - * - * } - * - * public Either createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - * - * Either result = null; - * - * log.trace("Going to create group {}" , groupDefinition); - * - * try { - * - * // 3. verify group not already exist List groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { - * - * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - * - * found = existGroupDef != null; } - * - * if (true == found) { String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), - * componentTypeForResponse)); return result; } - * - * // 4. verify type of group exist String groupType = groupDefinition.getType(); if (groupType == null || groupType.isEmpty()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, - * groupDefinition.getName())); return result; } Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); if (getGroupType.isRight()) { StorageOperationStatus status = - * getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); result = - * Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); return result; } else { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } } - * - * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - * - * Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - * - * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; } - * - * // 7. verify the artifacts belongs to the component Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); if (areValidArtifacts.isRight()) { - * ResponseFormat responseFormat = areValidArtifacts.right().value(); result = Either.right(responseFormat); return result; } - * - * NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); - * - * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID); - * - * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID); - * - * // add version groupDefinition.setVersion(INITIAL_VERSION); - * - * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - * - * Either addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); - * - * if (addGroupToGraph.isRight()) { StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); result = - * Either.right(componentsUtils.getResponseFormat(actionStatus)); log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); } else { GroupDefinition - * groupDefinitionCreated = addGroupToGraph.left().value(); result = Either.left(groupDefinitionCreated); } - * - * return result; - * - * } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - * - * public Either, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List groups, boolean inTransaction) { List updatedGroups = new ArrayList<>(); - * Either, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either updateGroupNameRes; Either validateGenerateGroupNameRes; int counter; for - * (GroupDefinition group : groups) { if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { continue; } counter = - * Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); if (validateGenerateGroupNameRes.isRight()) { - * updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; } updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); if - * (updateGroupNameRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); break; } - * updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; } - */ - - private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { - Either, ResponseFormat> result; - - Either, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); - if (eitherUpdate.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - } else { - result = Either.left(eitherUpdate.left().value()); - } - return result; - } - - public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { - Either validateGenerateGroupNamesRes = Either.left(true); - Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); - for (ArtifactTemplateInfo group : allGroups) { - Either validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++); - if (validateGenerateGroupNameRes.isRight()) { - validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); - break; - } - group.setGroupName(validateGenerateGroupNameRes.left().value()); - } - return validateGenerateGroupNamesRes; - } - - /** - * Generate module name from resourceName, description and counter - * - * @param resourceSystemName - * @param description - * @param groupCounter - * @return - */ - private Either validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) { - Either validateGenerateGroupNameRes; - if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) { - final String fileName = description.replaceAll("\\.\\.", "\\."); - validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter)); - } else { - validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME)); - } - return validateGenerateGroupNameRes; - } - - public Either, ResponseFormat> validateUpdateVfGroupNames(Map groups, String resourceSystemName) { - - Map updatedNamesGroups = new HashMap<>(); - Either, ResponseFormat> result = Either.left(updatedNamesGroups); - for (Entry groupEntry : groups.entrySet()) { - GroupDefinition curGroup = groupEntry.getValue(); - String groupType = curGroup.getType(); - String groupName = groupEntry.getKey(); - int counter; - String description; - Either newGroupNameRes; - if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) { - - if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) { - counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]); - description = curGroup.getDescription(); - } else { - counter = getNextVfModuleNameCounter(updatedNamesGroups); - description = groupName; - } - newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); - if (newGroupNameRes.isRight()) { - log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); - result = Either.right(newGroupNameRes.right().value()); - break; - } - groupName = newGroupNameRes.left().value(); - curGroup.setName(groupName); - } - updatedNamesGroups.put(groupName, curGroup); - } - return result; - } - - public int getNextVfModuleNameCounter(Map groups) { - int counter = 0; - if (groups != null && !groups.isEmpty()) { - counter = getNextVfModuleNameCounter(groups.values()); - } - return counter; - } - - public int getNextVfModuleNameCounter(Collection groups) { - int counter = 0; - if (groups != null && !groups.isEmpty()) { - List counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) - .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(Collectors.toList()); - counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1; - } - return counter; - } - - public Either, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List groups, Component component, boolean inTransaction) { - List updatedGroups = new ArrayList<>(); - Either, ResponseFormat> result = Either.left(updatedGroups); - - for (GroupDefinition group : groups) { - String groupType = group.getType(); - String oldGroupName = group.getName(); - String newGroupName; - Either newGroupNameRes; - Either updateGroupNameRes; - int counter; - if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) { - counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); - newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter); - if (newGroupNameRes.isRight()) { - log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); - result = Either.right(newGroupNameRes.right().value()); - break; - } - newGroupName = newGroupNameRes.left().value(); - group.setName(newGroupName); - - } - updatedGroups.add(group); - - } - - result = Either.left(updatedGroups); - return result; - } - - /* - * public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { - * - * List generatedGroups = new ArrayList<>(); Either, ResponseFormat> result = Either.left(generatedGroups); - * - * try { - * - * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, - * groupDefinition, true); if (createGroup.isRight()) { result = Either.right(createGroup.right().value()); return result; } GroupDefinition generatedGroup = createGroup.left().value(); generatedGroups.add(generatedGroup); } } - * - * return result; } finally { - * - * if (false == inTransaction) { - * - * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } - * - * } - * - * } - * - * } - */ - - public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { - Either result = null; - - // Validate user exist - Either validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - // Validate component exist - org.openecomp.sdc.be.model.Component component = null; - String realComponentId = componentId; - - try { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreArtifacts(false); - - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); - - if (findComponentInstanceAndGroupInstanceRes.isRight()) { - log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); - result = Either.right(responseFormat); - return result; - } - - GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); - ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft(); - - Boolean isBase = null;// Constants.IS_BASE; - List props = group.convertToGroupInstancesProperties(); - if (props != null && !props.isEmpty()) { - Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); - if (isBasePropOp.isPresent()) { - GroupProperty propIsBase = isBasePropOp.get(); - isBase = Boolean.parseBoolean(propIsBase.getValue()); - - } else { - BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); - // return - // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - - } - } - - List artifacts = new ArrayList<>(); - List artifactsIds = group.getArtifacts(); - if (artifactsIds != null && !artifactsIds.isEmpty()) { - - List instances = component.getComponentInstances(); - if (instances != null) { - Optional findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); - if (findFirst.isPresent()) { - ComponentInstance ci = findFirst.get(); - Map deploymentArtifacts = ci.getDeploymentArtifacts(); - for (String id : artifactsIds) { - Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - List instArtifactsIds = group.getGroupInstanceArtifacts(); - for (String id : instArtifactsIds) { - Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); - if (artOp.isPresent()) { - artifacts.add(new ArtifactDefinitionInfo(artOp.get())); - } - } - } - - } - } - GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); - resultInfo.setIsBase(isBase); - if (!artifacts.isEmpty()) - resultInfo.setArtifacts(artifacts); - - result = Either.left(resultInfo); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - } - - private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { - - Either, StorageOperationStatus> result = null; - if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { - Optional foundGroup; - Optional foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); - if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { - foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); - if (foundGroup.isPresent()) { - result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); - } - } - } - if (result == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - return result; - } - - private int getLatestIntProperty(Map newValues, Map parentValues, PropertyNames propertyKey) { - String value; - if (newValues.containsKey(propertyKey)) { - value = newValues.get(propertyKey); - } else { - value = parentValues.get(propertyKey); - } - return Integer.valueOf(value); - } - - private boolean isPropertyChanged(Map newValues, Map parentValues, final PropertyNames minInstances) { - return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); - } - - private Either validateMinMaxAndInitialCountPropertyLogicVF(Map newValues, Map parentValues) { - - int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); - int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); - int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); - Either result = Either.left(true); - - if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) { - if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); - } - } - if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) { - if (latestMaxInstances < latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); - } - - } - if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) { - if (latestMinInstances > latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); - } - - } - return result; - } - - private Either validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { - - Either result; - for (Entry entry : newValues.entrySet()) { - PropertyNames currPropertyName = entry.getKey(); - if (currPropertyName == PropertyNames.MIN_INSTANCES) { - String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); - String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { - String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); - String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { - String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), - new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if (result.isRight()) { - return result; - } - } - } - return Either.left(true); - } - - private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { - Either result; - final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; - int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); - int minInt = parseIntValue(min.getValue(), min.getKey()); - int maxInt = parseIntValue(max.getValue(), max.getKey()); - if (newValueInt < 0 || minInt < 0 || maxInt < 0) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); - } else if (newValueInt < minInt || newValueInt > maxInt) { - log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - result = Either - .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); - } else { - result = Either.left(true); - } - return result; - } - - private int parseIntValue(String value, PropertyNames propertyName) { - int result; - if (propertyName == PropertyNames.MAX_INSTANCES) { - result = convertIfUnboundMax(value); - } else if (NumberUtils.isNumber(value)) { - result = Integer.parseInt(value); - } else { - result = -1; - } - return result; - } - - /** - * validates received new property values and updates group instance in case of success - * - * @param oldGroupInstance - * @param groupInstanceId - * @param newProperties - * @param inTransaction - * @return - */ - public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties, boolean inTransaction) { - - Either actionResult = null; - Either updateGroupInstanceResult = null; - Either, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); - if (validateRes.isRight()) { - log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); - actionResult = Either.right(validateRes.right().value()); - } - if (actionResult == null) { - List validatedReducedNewProperties = validateRes.left().value(); - updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); - if (updateGroupInstanceResult.isRight()) { - log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); - } - } - if (actionResult == null) { - actionResult = Either.left(updateGroupInstanceResult.left().value()); - } - return actionResult; - } - - private Either, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { - - Either validationRes = null; - Either, ResponseFormat> actionResult; - Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - Map newPropertyValues = new EnumMap<>(PropertyNames.class); - List reducedProperties = new ArrayList<>(); - String currPropertyName; - try { - for (GroupInstanceProperty currNewProperty : newProperties) { - currPropertyName = currNewProperty.getName(); - validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); - if (validationRes.isRight()) { - log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); - break; - } - } - if (validationRes == null || validationRes.isLeft()) { - Map existingPropertyValues = new EnumMap<>(PropertyNames.class); - Map parentPropertyValues = new EnumMap<>(PropertyNames.class); - fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); - validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); - } - if (validationRes.isLeft()) { - actionResult = Either.left(reducedProperties); - } else { - actionResult = Either.right(validationRes.right().value()); - } - } catch (Exception e) { - log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return actionResult; - } - - private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, Map propertyValues, Map parentPropertyValues) { - PropertyNames[] allPropertyNames = PropertyNames.values(); - for (PropertyNames name : allPropertyNames) { - if (isUpdatable(name)) { - propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); - parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); - } - } - } - - private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { - - Either validationRes = null; - String currPropertyName = currNewProperty.getName(); - PropertyNames propertyName = PropertyNames.findName(currPropertyName); - try { - if (currExistingProperty == null) { - log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); - } else if (isUpdatable(propertyName)) { - validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); - if (validationRes.isRight()) { - log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); - } else { - addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); - } - } else { - validateImmutableProperty(currExistingProperty, currNewProperty); - } - if (validationRes == null) { - validationRes = Either.left(true); - } - } catch (Exception e) { - log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); - validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return validationRes; - } - - private boolean isUpdatable(PropertyNames updatablePropertyName) { - return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); - } - - private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - String newValue = newProperty.getValue(); - if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { - newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); - reducedProperties.add(newProperty); - } - if (!isEmptyMinInitialCountValue(propertyName, newValue)) { - newPropertyValues.put(propertyName, newValue); - } - } - - private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { - boolean result = false; - if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { - result = true; - } - return result; - } - - private int convertIfUnboundMax(String value) { - - int result; - if (!NumberUtils.isNumber(value)) { - result = Integer.MAX_VALUE; - } else { - result = Integer.parseInt(value); - } - return result; - } - - private Either validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - Either validationRes = null; - String parentValue = existingProperty.getParentValue(); - - newProperty.setParentValue(parentValue); - if (StringUtils.isEmpty(newProperty.getValue())) { - newProperty.setValue(parentValue); - } - if (StringUtils.isEmpty(existingProperty.getValue())) { - existingProperty.setValue(parentValue); - } - StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); - if (status != StorageOperationStatus.OK) { - log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); - validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); - } - if (validationRes == null) { - validationRes = Either.left(true); - } - return validationRes; - } - - private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { - if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { - log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); - } - } - - public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - - Map groups = new HashMap<>(); - // Map groupsPropertiesMap = new HashMap<>(); - Either, ResponseFormat> result = null; - Either, StorageOperationStatus> createGroupsResult = null; - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - - } - - // handle groups and convert to tosca data - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); - if (handleGroupRes.isRight()) { - result = Either.right(handleGroupRes.right().value()); - break; - } - GroupDefinition handledGroup = handleGroupRes.left().value(); - groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); - - } - } - if (result == null) { - createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - } - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - - Either, ResponseFormat> result = null; - Either, StorageOperationStatus> createGroupsResult = null; - List groups = new ArrayList<>(); - - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); - - } - - // handle groups and convert to tosca data - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); - if (handleGroupRes.isRight()) { - result = Either.right(handleGroupRes.right().value()); - break; - } - GroupDefinition handledGroup = handleGroupRes.left().value(); - groups.add(new GroupDataDefinition(handledGroup)); - } - } - if (result == null) { - createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - } - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - - Either, ResponseFormat> result = null; - Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - /** - * Update specific group version - * - * @param groupDefinition - * @param inTransaction - * @return - */ - public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { - - Either, ResponseFormat> result = null; - Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); - if (createGroupsResult.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if (result == null) { - result = Either.left(createGroupsResult.left().value()); - } - return result; - } - - public Either handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map allDAtaTypes) { - - Either result = null; - - log.trace("Going to create group {}", groupDefinition); - // 3. verify group not already exist - List groups = component.getGroups(); - boolean found = false; - if (groups != null && false == groups.isEmpty()) { - - GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - - found = existGroupDef != null; - } - if (true == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse)); - return result; - } - // 4. verify type of group exist - String groupType = groupDefinition.getType(); - if (groupType == null || groupType.isEmpty()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName())); - return result; - } - Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - if (getGroupType.isRight()) { - StorageOperationStatus status = getGroupType.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - return result; - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - } - // 6. verify the component instances type are allowed according to - // the member types in the group type - GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - - Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - - if (areValidMembers.isRight()) { - ResponseFormat responseFormat = areValidMembers.right().value(); - result = Either.right(responseFormat); - return result; - } - // 7. verify the artifacts belongs to the component - Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); - if (areValidArtifacts.isRight()) { - ResponseFormat responseFormat = areValidArtifacts.right().value(); - result = Either.right(responseFormat); - return result; - } - List groupTypeProperties = groupTypeDefinition.getProperties(); - - List properties = groupDefinition.convertToGroupProperties(); - List updatedGroupTypeProperties = new ArrayList<>(); - if (properties != null && false == properties.isEmpty()) { - - if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); - } - - Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - - Either addPropertyResult = null; - int i = 1; - for (GroupProperty prop : properties) { - addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes); - if (addPropertyResult.isRight()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); - } - updatedGroupTypeProperties.add(addPropertyResult.left().value()); - - i++; - } - } - if (groupDefinition.getUniqueId() == null) { - String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName()); - groupDefinition.setUniqueId(uid); - } - groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); - groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); - groupDefinition.setVersion(INITIAL_VERSION); - groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - - return Either.left(groupDefinition); - } - - public Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes) { - - if (prop == null) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - - PropertyDataDefinition propDataDef = prop; - String propertyType = propDataDef.getType(); - String value = groupProperty.getValue(); - - Either checkInnerType = propertyOperation.checkInnerType(propDataDef); - if (checkInnerType.isRight()) { - TitanOperationStatus status = checkInnerType.right().value(); - return Either.right(status); - } - - String innerType = checkInnerType.left().value(); - - log.debug("Before validateAndUpdatePropertyValue"); - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); - log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index); - - groupProperty.setUniqueId(uniqueId); - groupProperty.setValue(newValue); - groupProperty.setType(prop.getType()); - groupProperty.setDefaultValue(prop.getDefaultValue()); - groupProperty.setDescription(prop.getDescription()); - groupProperty.setSchema(prop.getSchema()); - groupProperty.setPassword(prop.isPassword()); - groupProperty.setParentUniqueId(prop.getUniqueId()); - - log.debug("Before adding property value to graph {}", groupProperty); - - return Either.left(groupProperty); - } + public static final String GROUP_DELIMITER_REGEX = "\\.\\."; + private static String ADDING_GROUP = "AddingGroup"; + + public static final String INITIAL_VERSION = "1"; + + private static final String CREATE_GROUP = "CreateGroup"; + + private static final String UPDATE_GROUP = "UpdateGroup"; + + private static final String GET_GROUP = "GetGroup"; + + private static final String DELETE_GROUP = "GetGroup"; + + private static final Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class); + + @javax.annotation.Resource + private AccessValidations accessValidations; + + @javax.annotation.Resource + private GroupTypeOperation groupTypeOperation; + + @Autowired + private ArtifactsOperations artifactsOperation; + + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { + String componentTypeForResponse = "SERVICE"; + if (component instanceof Resource) { + componentTypeForResponse = ((Resource) component).getResourceType().name(); + } + return componentTypeForResponse; + } + + /** + * Verify that the artifact members belongs to the component + * + * @param component + * @param artifacts + * @return + */ + private Either verifyArtifactsBelongsToComponent(Component component, List artifacts, String context) { + + if (CollectionUtils.isEmpty(artifacts)) { + return Either.left(true); + } + + Map deploymentArtifacts = component.getDeploymentArtifacts(); + if (MapUtils.isEmpty(deploymentArtifacts)) { + BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + List currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(toList()); + log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); + if (!currentArtifacts.containsAll(artifacts)) { + BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return Either.left(true); + + } + + /** + * verify that the members are component instances of the component + * + * @param component + * @param groupMembers + * @param memberToscaTypes + * @return + */ + private Either verifyComponentInstancesAreValidMembers(Component component, String groupName, Map groupMembers, List memberToscaTypes) { + + if (MapUtils.isEmpty(groupMembers)) { + return Either.left(true); + } + + if (CollectionUtils.isEmpty(memberToscaTypes)) { + return Either.left(true); + } + + List componentInstances = component.getComponentInstances(); + if (CollectionUtils.isNotEmpty(componentInstances)) { + Map compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); + + Set allCompInstances = compInstUidToCompInstMap.keySet(); + + for (Entry groupMember : groupMembers.entrySet()) { + String compName = groupMember.getKey(); + String compUid = groupMember.getValue(); + + if (!allCompInstances.contains(compUid)) { + /* + * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ] + */ + String componentTypeForResponse = getComponentTypeForResponse(component); + + BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse)); + } + } + } + + return Either.left(true); + } + + + + /** + * Update GroupDefinition metadata + * + * @param componentId + * @param user + * @param componentType + * @param updatedGroup + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) { + + Either result = null; + try { + // Validate user exist + Either validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + // Validate component exist + Either validateComponent = validateComponentExists(componentId, componentType, null); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + org.openecomp.sdc.be.model.Component component = validateComponent.left().value(); + // validate we can work on component + Either canWork = validateCanWorkOnComponent(component, user.getUserId()); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + List currentGroups = component.getGroups(); + if (CollectionUtils.isEmpty(currentGroups)) { + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + // Validate groups exists in the component + Optional currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); + if (!currentGroupOpt.isPresent()) { + log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); + return result; + } + GroupDefinition currentGroup = currentGroupOpt.get(); + if ( shouldLock ){ + Either lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata"); + if (lockResult.isRight()) { + result = Either.right(lockResult.right().value()); + return result; + } + } + // Validate group type is vfModule + if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) { + log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType()); + result = Either.right(responseFormat); + return result; + } + result = updateGroupMetadata(component, currentGroup, updatedGroup); + return result; + + } finally { + if (result.isLeft()) { + titanDao.commit(); + } else { + titanDao.rollback(); + } + if (shouldLock) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + } + } + + private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { + String currentGroupName = currentGroup.getName(); + Either result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); + + if (result.isRight()) { + log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + } + if (result.isLeft()) { + result = updateGroup(component, currentGroup, currentGroupName); + } + return result; + } + + private Either updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { + Either handleGroupRes; + Either result = null; + if (updatedGroup.getName().equals(currentGroupName)) { + handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); + if (handleGroupRes.isRight()) { + log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } else { + StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); + if (deleteStatus != StorageOperationStatus.OK) { + log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); + } + handleGroupRes = groupsOperation.addGroup(component, updatedGroup); + if (handleGroupRes.isRight()) { + log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); + } + } + if (result == null) { + result = Either.left(updatedGroup); + } + return result; + } + + /** + * Validate and Update Group Property + * + * @param componentId + * @param groupUniqueId + * @param user + * @param componentType + * @param groupPropertiesToUpdate + * @param inTransaction + * @return + */ + public Either, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List groupPropertiesToUpdate, boolean inTransaction) { + + Either, ResponseFormat> result = Either.left(groupPropertiesToUpdate); + try { + Optional optionalGroupConnectedToVf = null; + GroupDefinition currentGroup = null; + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); + if (lockResult != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); + } + if (result.isLeft()) { + // VF exist because lock succedded + Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); + optionalGroupConnectedToVf = + // All groups on resource + vf.getGroups().stream(). + // Filter in group sent is part of VF groups + filter(e -> e.getUniqueId().equals(groupUniqueId)). + // Collect + findAny(); + if (!optionalGroupConnectedToVf.isPresent()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); + } + } + + if (result.isLeft()) { + currentGroup = optionalGroupConnectedToVf.get(); + result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); + } + if (result.isLeft()) { + result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); + if (result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); + log.debug("failed to update Vf {}", componentId); + } + } + + } catch (Exception e) { + log.debug("Error in validateAndUpdateGroupProperty {}", e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + return result; + } + + private void resetEmptyValueWithDefaults(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + Map originalProperties = + // Stream of original properties from group + originalGroup.convertToGroupProperties().stream(). + // Collecting to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + for (GroupProperty gp : groupPropertiesToUpdate) { + if (StringUtils.isEmpty(gp.getValue())) { + gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); + } + } + + } + + private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List groupPropertiesToUpdate) { + + Either, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); + if (ret.isLeft()) { + resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); + } + if (ret.isLeft()) { + // Validate Type Match Value + Optional optionalError = + // Stream of group properties + groupPropertiesToUpdate.stream(). + // Validate each and map to returned Strorage status value + map(e -> groupOperation.validateAndUpdatePropertyValue(e)). + // Keep only failed result if there is such + filter(e -> e != StorageOperationStatus.OK). + // collect + findFirst(); + if (optionalError.isPresent()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); + ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + } + if (ret.isLeft()) { + // Validate min max ect... + ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); + } + + return ret; + } + + private Either, ResponseFormat> validatePropertyBusinessLogic(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + + Map nameValueMap = new HashMap<>(); + for (GroupProperty gp : groupPropertiesToUpdate) { + // Filter out non special properties which does not have Enum + final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); + if (gpEnum != null) { + nameValueMap.put(gpEnum, gp.getValue()); + } + } + + if (!MapUtils.isEmpty(nameValueMap)) { + + if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { + + Map oldValueMap = prepareMapWithOriginalProperties(originalGroup); + + Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); + if (eitherValid.isRight()) { + ret = Either.right(eitherValid.right().value()); + } + } + if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { + + Optional optionalError = + // Stream of group Properties + groupPropertiesToUpdate.stream(). + // Filter in only properties that needs text validation + filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). + // validate text properties + map(e -> validateFreeText(e)). + // filter in only errors if exist + filter(e -> e.isRight()). + // map the Either value to the Error + map(e -> e.right().value()) + // collect + .findFirst(); + if (optionalError.isPresent()) { + ret = Either.right(optionalError.get()); + } + + } + } + + return ret; + } + + private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { + Map oldValueMap = new HashMap<>(); + PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; + + for (GroupProperty gp : originalGroup.convertToGroupProperties()) { + if (enumHasValueFilter(gp.getName(), PropertyNames::findName, propertiesToCheck)) { + oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); + } + } + if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { + oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); + } + return oldValueMap; + } + + private Either, ResponseFormat> validateOnlyValueChanged(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); + if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); + } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); + } else { + Map namePropertyMap = + // Original Group Properties Stream + originalGroup.convertToGroupProperties().stream(). + // Collect to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + + Optional optionalMissingProperty = + // Group Properties to be updated Stream + groupPropertiesToUpdate.stream(). + // Filter in property that is not contained in original if there is such + filter(e -> !namePropertyMap.containsKey(e.getName())). + // collect + findFirst(); + + if (optionalMissingProperty.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); + } else { + Optional optionalNonValueChange = + // groups to be updated stream + groupPropertiesToUpdate.stream(). + // filter in only properties with non-value (illegal) change + filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). + // Collect + findFirst(); + if (optionalNonValueChange.isPresent()) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); + + } + } + + } + return ret; + } + + /** + * if groupProperty are the same or if only value is different returns true, otherwise returns false. + * + * @param groupProperty + * @param groupProperty2 + * @return + */ + private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { + // Create 2 duplicates for groupPropery and reset their values + try { + GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); + groupPropertyDuplicate.setValue(null); + groupPropertyDuplicate.setSchema(null); + groupPropertyDuplicate.setParentUniqueId(null); + GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); + groupProperty2Duplicate.setValue(null); + groupProperty2Duplicate.setSchema(null); + groupProperty2Duplicate.setParentUniqueId(null); + return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()); + } catch (Exception e) { + log.debug("Failed validate group properties. ", e); + return false; + } + } + + /** + * Validate and update GroupDefinition metadata + * + * @param currentGroup + * @param groupUpdate + * @return + **/ + private Either validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) { + // Check if to update, and update GroupDefinition name. + Either response = validateAndUpdateGroupName(currentGroup, groupUpdate); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + // Do not allow to update GroupDefinition version directly. + String versionUpdated = groupUpdate.getVersion(); + String versionCurrent = currentGroup.getVersion(); + if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { + log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); + } + + return Either.left(currentGroup); + } + + /** + * Validate and update GroupDefinition name + * + * @param currentGroup + * @param groupUpdate + * @return + */ + private Either validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) { + String nameUpdated = groupUpdate.getName(); + String nameCurrent = currentGroup.getName(); + if (!nameCurrent.equals(nameUpdated)) { + Either validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true); + if (validatNameResponse.isRight()) { + ResponseFormat errorRespons = validatNameResponse.right().value(); + return Either.right(errorRespons); + } + currentGroup.setName(groupUpdate.getName()); + } + return Either.left(true); + } + + /** + * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part + * MyDesc was changed. + * + * @param currentGroupName + * @param groupUpdateName + * @return + */ + private Either validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) { + try { + // Check if the group name is in old format. + if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) { + log.error("Group name {} is in old format", groupUpdateName); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName)); + } + + // Check that name pats 1 and 3 did not changed (only the second + // part can be changed) + // But verify before that the current group format is the new one + if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) { + String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX); + String currentResourceName = split1[0]; + String currentCounter = split1[2]; + + String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX); + String groupUpdateResourceName = split2[0]; + String groupUpdateCounter = split2[2]; + if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes] + if (!currentResourceName.equals(groupUpdateResourceName)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName)); + } + + if (!currentCounter.equals(groupUpdateCounter)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter)); + } + } + + } + + return Either.left(true); + } catch (Exception e) { + log.error("Error valiadting group name", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + + + /** + * associate artifacts to a given group + * + * @param componentId + * @param userId + * @param componentType + * @param inTransaction + * @return + */ + public Either getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) { + + Either result = null; + + // Validate user exist + Either validateUserExists = validateUserExists(userId, GET_GROUP, true); + + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + + // Validate component exist + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentId; + + try { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreGroups(false); + componentParametersView.setIgnoreArtifacts(false); + componentParametersView.setIgnoreUsers(false); + + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + Either groupEither = findGroupOnComponent(component, groupId); + + if (groupEither.isRight()) { + log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); + String componentTypeForResponse = getComponentTypeForResponse(component); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); + return result; + } + GroupDefinition group = groupEither.left().value(); + + Boolean isBase = null; + List props = group.convertToGroupProperties(); + if (props != null && !props.isEmpty()) { + Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + } + } + + List artifacts = new ArrayList<>(); + List artifactsFromComponent = new ArrayList<>(); + List artifactsIds = group.getArtifacts(); + + Map deploymentArtifacts = null; + if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { + deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); + } + + if (artifactsIds != null && !artifactsIds.isEmpty()) { + for (String id : artifactsIds) { + if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { + log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); + result = Either.right(responseFormat); + return result; + } + artifactsFromComponent.add(deploymentArtifacts.get(id)); + } + if (!artifactsFromComponent.isEmpty()) { + for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { + ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); + artifacts.add(artifactDefinitionInfo); + } + } + + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) { + resultInfo.setArtifacts(artifacts); + } + result = Either.left(resultInfo); + + return result; + + } finally { + + if (!inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + + } + + private Either findGroupOnComponent(Component component, String groupId) { + + Either result = null; + if (CollectionUtils.isNotEmpty(component.getGroups())) { + Optional foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); + if (foundGroup.isPresent()) { + result = Either.left(foundGroup.get()); + } + } + if (result == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + + public String getAsString(List list) { + + if (list == null || list.isEmpty()) { + return ""; + } + StringBuilder builder = new StringBuilder(); + list.forEach(p -> builder.append(p + ",")); + + String result = builder.toString(); + return result.substring(0, result.length()); + + } + + + private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { + Either, ResponseFormat> result; + + Either, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); + if (eitherUpdate.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + } else { + result = Either.left(eitherUpdate.left().value()); + } + return result; + } + + public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { + Either validateGenerateGroupNamesRes = Either.left(true); + Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); + for (ArtifactTemplateInfo group : allGroups) { + Either validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++); + if (validateGenerateGroupNameRes.isRight()) { + validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); + break; + } + group.setGroupName(validateGenerateGroupNameRes.left().value()); + } + return validateGenerateGroupNamesRes; + } + + /** + * Generate module name from resourceName, description and counter + * + * @param resourceSystemName + * @param description + * @param groupCounter + * @return + */ + private Either validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) { + Either validateGenerateGroupNameRes; + if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) { + final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\."); + validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter)); + } else { + validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME)); + } + return validateGenerateGroupNameRes; + } + + public Either, ResponseFormat> validateUpdateVfGroupNames(Map groups, String resourceSystemName) { + + Map updatedNamesGroups = new HashMap<>(); + Either, ResponseFormat> result = Either.left(updatedNamesGroups); + for (Entry groupEntry : groups.entrySet()) { + GroupDefinition curGroup = groupEntry.getValue(); + String groupType = curGroup.getType(); + String groupName = groupEntry.getKey(); + int counter; + String description; + Either newGroupNameRes; + if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) { + + if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) { + counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]); + description = curGroup.getDescription(); + } else { + counter = getNextVfModuleNameCounter(updatedNamesGroups); + description = groupName; + } + newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter); + if (newGroupNameRes.isRight()) { + log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); + result = Either.right(newGroupNameRes.right().value()); + break; + } + groupName = newGroupNameRes.left().value(); + curGroup.setName(groupName); + } + updatedNamesGroups.put(groupName, curGroup); + } + return result; + } + + public int getNextVfModuleNameCounter(Map groups) { + int counter = 0; + if (groups != null && !groups.isEmpty()) { + counter = getNextVfModuleNameCounter(groups.values()); + } + return counter; + } + + public int getNextVfModuleNameCounter(Collection groups) { + int counter = 0; + if (groups != null && !groups.isEmpty()) { + List counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) + .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList()); + counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1; + } + return counter; + } + + public Either, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List groups, Component component, boolean inTransaction) { + List updatedGroups = new ArrayList<>(); + Either, ResponseFormat> result = Either.left(updatedGroups); + + for (GroupDefinition group : groups) { + String groupType = group.getType(); + String oldGroupName = group.getName(); + String newGroupName; + Either newGroupNameRes; + int counter; + if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) { + counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); + newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter); + if (newGroupNameRes.isRight()) { + log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value()); + result = Either.right(newGroupNameRes.right().value()); + break; + } + newGroupName = newGroupNameRes.left().value(); + group.setName(newGroupName); + + } + updatedGroups.add(group); + + } + + result = Either.left(updatedGroups); + return result; + } + + + public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { + Either result = null; + + // Validate user exist + Either validateUserExists = validateUserExists(userId, UPDATE_GROUP, true); + + if (validateUserExists.isRight()) { + result = Either.right(validateUserExists.right().value()); + return result; + } + + // Validate component exist + org.openecomp.sdc.be.model.Component component = null; + String realComponentId = componentId; + + try { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreArtifacts(false); + + Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); + + if (findComponentInstanceAndGroupInstanceRes.isRight()) { + log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); + result = Either.right(responseFormat); + return result; + } + + GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); + + Boolean isBase = null; + List props = group.convertToGroupInstancesProperties(); + if (props != null && !props.isEmpty()) { + Optional isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny(); + if (isBasePropOp.isPresent()) { + GroupProperty propIsBase = isBasePropOp.get(); + isBase = Boolean.parseBoolean(propIsBase.getValue()); + + } else { + BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO); + } + } + + List artifacts = new ArrayList<>(); + List artifactsIds = group.getArtifacts(); + if (artifactsIds != null && !artifactsIds.isEmpty()) { + + List instances = component.getComponentInstances(); + if (instances != null) { + Optional findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance ci = findFirst.get(); + Map deploymentArtifacts = ci.getDeploymentArtifacts(); + for (String id : artifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + List instArtifactsIds = group.getGroupInstanceArtifacts(); + for (String id : instArtifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + } + + } + } + GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); + resultInfo.setIsBase(isBase); + if (!artifacts.isEmpty()) { + resultInfo.setArtifacts(artifacts); + } + result = Either.left(resultInfo); + + return result; + + } finally { + + if (!inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + } + + private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { + + Either, StorageOperationStatus> result = null; + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { + Optional foundGroup; + Optional foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); + if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { + foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); + if (foundGroup.isPresent()) { + result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); + } + } + } + if (result == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + return result; + } + + private int getLatestIntProperty(Map newValues, Map parentValues, PropertyNames propertyKey) { + String value; + if (newValues.containsKey(propertyKey)) { + value = newValues.get(propertyKey); + } else { + value = parentValues.get(propertyKey); + } + return Integer.valueOf(value); + } + + private boolean isPropertyChanged(Map newValues, Map parentValues, final PropertyNames minInstances) { + return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); + } + + private Either validateMinMaxAndInitialCountPropertyLogicVF(Map newValues, Map parentValues) { + + int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); + int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); + int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); + Either result = Either.left(true); + + if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft() + && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft() && + latestMaxInstances < latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); + } + if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && + result.isLeft() && latestMinInstances > latestInitialCount) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); + } + return result; + } + + private Either validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { + + Either result; + for (Entry entry : newValues.entrySet()) { + PropertyNames currPropertyName = entry.getKey(); + if (currPropertyName == PropertyNames.MIN_INSTANCES) { + String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { + String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); + String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { + String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); + String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); + if (result.isRight()) { + return result; + } + } + } + return Either.left(true); + } + + private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { + Either result; + final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; + int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); + int minInt = parseIntValue(min.getValue(), min.getKey()); + int maxInt = parseIntValue(max.getValue(), max.getKey()); + if (newValueInt < 0 || minInt < 0 || maxInt < 0) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); + } else if (newValueInt < minInt || newValueInt > maxInt) { + log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); + result = Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); + } else { + result = Either.left(true); + } + return result; + } + + private int parseIntValue(String value, PropertyNames propertyName) { + int result; + if (propertyName == PropertyNames.MAX_INSTANCES) { + result = convertIfUnboundMax(value); + } else if (NumberUtils.isNumber(value)) { + result = Integer.parseInt(value); + } else { + result = -1; + } + return result; + } + + /** + * validates received new property values and updates group instance in case of success + * + * @param oldGroupInstance + * @param newProperties + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties, boolean inTransaction) { + + Either actionResult = null; + Either updateGroupInstanceResult = null; + Either, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); + if (validateRes.isRight()) { + log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); + actionResult = Either.right(validateRes.right().value()); + } + if (actionResult == null) { + List validatedReducedNewProperties = validateRes.left().value(); + updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); + if (updateGroupInstanceResult.isRight()) { + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); + } + } + if (actionResult == null) { + actionResult = Either.left(updateGroupInstanceResult.left().value()); + } + return actionResult; + } + + private Either, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { + + Either validationRes = null; + Either, ResponseFormat> actionResult; + Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + Map newPropertyValues = new EnumMap<>(PropertyNames.class); + List reducedProperties = new ArrayList<>(); + String currPropertyName; + try { + for (GroupInstanceProperty currNewProperty : newProperties) { + currPropertyName = currNewProperty.getName(); + validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); + if (validationRes.isRight()) { + log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); + break; + } + } + if (validationRes == null || validationRes.isLeft()) { + Map existingPropertyValues = new EnumMap<>(PropertyNames.class); + Map parentPropertyValues = new EnumMap<>(PropertyNames.class); + fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); + validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); + } + if (validationRes.isLeft()) { + actionResult = Either.left(reducedProperties); + } else { + actionResult = Either.right(validationRes.right().value()); + } + } catch (Exception e) { + log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return actionResult; + } + + private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, Map propertyValues, Map parentPropertyValues) { + PropertyNames[] allPropertyNames = PropertyNames.values(); + for (PropertyNames name : allPropertyNames) { + if (isUpdatable(name)) { + propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); + parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); + } + } + } + + private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + + Either validationRes = null; + String currPropertyName = currNewProperty.getName(); + PropertyNames propertyName = PropertyNames.findName(currPropertyName); + try { + if (currExistingProperty == null) { + log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); + } else if (isUpdatable(propertyName)) { + validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); + if (validationRes.isRight()) { + log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); + } else { + addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); + } + } else { + validateImmutableProperty(currExistingProperty, currNewProperty); + } + if (validationRes == null) { + validationRes = Either.left(true); + } + } catch (Exception e) { + log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); + validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return validationRes; + } + + private boolean isUpdatable(PropertyNames updatablePropertyName) { + return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + } + + private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + String newValue = newProperty.getValue(); + if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { + newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); + reducedProperties.add(newProperty); + } + if (!isEmptyMinInitialCountValue(propertyName, newValue)) { + newPropertyValues.put(propertyName, newValue); + } + } + + private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { + boolean result = false; + if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { + result = true; + } + return result; + } + + private int convertIfUnboundMax(String value) { + + int result; + if (!NumberUtils.isNumber(value)) { + result = Integer.MAX_VALUE; + } else { + result = Integer.parseInt(value); + } + return result; + } + + private Either validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + Either validationRes = null; + String parentValue = existingProperty.getParentValue(); + + newProperty.setParentValue(parentValue); + if (StringUtils.isEmpty(newProperty.getValue())) { + newProperty.setValue(parentValue); + } + if (StringUtils.isEmpty(existingProperty.getValue())) { + existingProperty.setValue(parentValue); + } + StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); + validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); + } + if (validationRes == null) { + validationRes = Either.left(true); + } + return validationRes; + } + + private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { + if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { + log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); + } + } + + public GroupDefinition createGroup(String groupType, ComponentTypeEnum componentTypeEnum, String componentId, + String userId) { + + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, CREATE_GROUP); + + validateGroupTypePerComponent(groupType, component); + + GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false) + .left() + .on(se -> onGroupTypeNotFound(component)); + + boolean isFirstGroup = component.getGroups() == null; + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setType(groupType); + + //find next valid counter + int nextCounter = 0; + if (!isFirstGroup) { + nextCounter = getNewGroupCounter(component); + } + String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter); + groupDefinition.setName(name); + + //Add default type properties + List groupTypeProperties = groupTypeDefinition.getProperties(); + List properties = groupTypeProperties.stream() + .map(GroupProperty::new) + .collect(toList()); + groupDefinition.convertFromGroupProperties(properties); + + List gdList; + if (isFirstGroup) { + gdList = createGroups(component, Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + } else { + gdList = addGroups(component, Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + } + return gdList.get(0); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private void validateGroupTypePerComponent(String groupType, Component component) { + String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType(); + if (!component.isTopologyTemplate()) { + throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, + specificType); + } + Map> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludedGroupTypesMapping(); + + if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) { + Set excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType); + if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) { + throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType); + } + } + } + + private int getNewGroupCounter(Component component) { + List existingNames = component.getGroups() + .stream() + .map(GroupDataDefinition::getName) + .collect(toList()); + List existingIds = component.getGroups() + .stream() + .map(GroupDataDefinition::getUniqueId) + .collect(toList()); + existingIds.addAll(existingNames); + + return Utils.getNextCounter(existingIds); + } + + public GroupDefinition updateGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId, + String userId, GroupDefinition updatedGroup) { + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, UPDATE_GROUP); + + GroupDefinition existingGroup = findGroupOnComponent(component, groupId) + .left() + .on(se -> onGroupNotFoundInComponentError(component, groupId)); + + String existingGroupName = existingGroup.getName(); + String updatedGroupName = updatedGroup.getName(); + assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component); + existingGroup.setName(updatedGroupName); + + return updateGroup(component, existingGroup, existingGroupName) + .left() + .on(this::onFailedUpdateGroupDBOperation); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + + } + + private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) { + if (!ValidationUtils.validateResourceInstanceNameLength(updatedGroupName)) { + throw new ComponentException(ActionStatus.EXCEEDS_LIMIT, "Group Name", ValidationUtils.RSI_NAME_MAX_LENGTH.toString()); + } + if (!ValidationUtils.validateResourceInstanceName(updatedGroupName)) { + throw new ComponentException(ActionStatus.INVALID_VF_MODULE_NAME, updatedGroupName); + } + if (!ComponentValidations.validateNameIsUniqueInComponent(currentGroupName, updatedGroupName, component)) { + throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, "Group", updatedGroupName); + } + } + + public GroupDefinition deleteGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId, + String userId) { + try { + Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, DELETE_GROUP); + + GroupDefinition groupDefinition = findGroupOnComponent(component, groupId) + .left() + .on(se -> onGroupNotFoundInComponentError(component, groupId)); + + List gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition)) + .left() + .on(this::onFailedGroupDBOperation); + return gdList.get(0); + } finally { + titanDao.commit(); + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + + private List onFailedGroupDBOperation(ResponseFormat responseFormat) { + titanDao.rollback(); + throw new ComponentException(responseFormat); + } + + private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) { + titanDao.rollback(); + throw new ComponentException(responseFormat); + } + + private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) { + throw new ComponentException(ActionStatus.GROUP_IS_MISSING, groupId, + component.getSystemName(), getComponentTypeForResponse(component)); + } + + private GroupTypeDefinition onGroupTypeNotFound(Component component) { + throw new ComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(), + component.getComponentType().toString()); + } + + private Boolean onFailedToLockComponent(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } + + + public Either, ResponseFormat> createGroups(Component component, final List groupDefinitions) { + + Map groups = new HashMap<>(); + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + // handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); + + } + } + if (result == null) { + createGroupsResult = groupsOperation.createGroups(component, groups); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either, ResponseFormat> addGroups(Component component, final List groupDefinitions) { + + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult = null; + List groups = new ArrayList<>(); + + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)))); + + } + + // handle groups and convert to tosca data + if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + for (GroupDefinition groupDefinition : groupDefinitions) { + Either handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value()); + if (handleGroupRes.isRight()) { + result = Either.right(handleGroupRes.right().value()); + break; + } + GroupDefinition handledGroup = handleGroupRes.left().value(); + groups.add(new GroupDataDefinition(handledGroup)); + } + } + if (result == null) { + createGroupsResult = groupsOperation.addGroups(component, groups); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + } + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either, ResponseFormat> deleteGroups(Component component, List groupDefinitions) { + + Either, StorageOperationStatus> deleteGroupsResult; + + deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(toList())); + if (deleteGroupsResult.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value()))); + } + return Either.left(deleteGroupsResult.left().value()); + } + + /** + * Update specific group version + * + */ + public Either, ResponseFormat> updateGroups(Component component, List groupDefinitions) { + + Either, ResponseFormat> result = null; + Either, StorageOperationStatus> createGroupsResult; + + createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { + result = Either.left(createGroupsResult.left().value()); + } + return result; + } + + public Either handleGroup(Component component, GroupDefinition groupDefinition, Map allDAtaTypes) { + + log.trace("Going to create group {}", groupDefinition); + // 3. verify group not already exist + String groupDefinitionName = groupDefinition.getName(); + if (groupExistsInComponent(groupDefinitionName, component)) { + String componentTypeForResponse = getComponentTypeForResponse(component); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse)); + } + // 4. verify type of group exist + String groupType = groupDefinition.getType(); + if (StringUtils.isEmpty(groupType)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinitionName)); + } + Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); + if (getGroupType.isRight()) { + StorageOperationStatus status = getGroupType.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); + } else { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + // 6. verify the component instances type are allowed according to + // the member types in the group type + GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); + + Either areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); + + if (areValidMembers.isRight()) { + ResponseFormat responseFormat = areValidMembers.right().value(); + return Either.right(responseFormat); + } + // 7. verify the artifacts belongs to the component + Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); + if (areValidArtifacts.isRight()) { + ResponseFormat responseFormat = areValidArtifacts.right().value(); + return Either.right(responseFormat); + } + List groupTypeProperties = groupTypeDefinition.getProperties(); + + List properties = groupDefinition.convertToGroupProperties(); + List updatedGroupTypeProperties = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(properties)) { + if (CollectionUtils.isEmpty(groupTypeProperties)) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND)))); + } + + Map groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + + Either addPropertyResult; + int i = 1; + for (GroupProperty prop : properties) { + addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType); + if (addPropertyResult.isRight()) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); + } + updatedGroupTypeProperties.add(addPropertyResult.left().value()); + + i++; + } + } + if (groupDefinition.getUniqueId() == null) { + String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName); + groupDefinition.setUniqueId(uid); + } + groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); + groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); + groupDefinition.setVersion(INITIAL_VERSION); + groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + + return Either.left(groupDefinition); + } + + private static boolean groupExistsInComponent(String groupDefinitionName, Component component) { + boolean found = false; + List groups = component.getGroups(); + if (CollectionUtils.isNotEmpty(groups)) { + found = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinitionName)).findFirst().orElse(null) != null; + } + return found; + } + + private Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes, String groupType) { + + if (prop == null) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + + PropertyDataDefinition propDataDef = prop; + String propertyType = propDataDef.getType(); + String value = groupProperty.getValue(); + + Either checkInnerType = propertyOperation.checkInnerType(propDataDef); + if (checkInnerType.isRight()) { + TitanOperationStatus status = checkInnerType.right().value(); + return Either.right(status); + } + + String innerType = checkInnerType.left().value(); + + log.debug("Before validateAndUpdatePropertyValue"); + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); + log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (!res) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) + : prop.getUniqueId(); + + groupProperty.setUniqueId(uniqueId); + groupProperty.setValue(newValue); + groupProperty.setType(prop.getType()); + groupProperty.setDefaultValue(prop.getDefaultValue()); + groupProperty.setDescription(prop.getDescription()); + groupProperty.setSchema(prop.getSchema()); + groupProperty.setPassword(prop.isPassword()); + groupProperty.setParentUniqueId(prop.getUniqueId()); + + log.debug("Before adding property value to graph {}", groupProperty); + + return Either.left(groupProperty); + } + + // For old groups we want to leave indexing of property + // For new groups we just need the types + private boolean shouldReconstructUniqueId(String groupType) { + return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java new file mode 100644 index 0000000000..cdd1b30656 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java @@ -0,0 +1,46 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +@Component +public class GroupTypeBusinessLogic { + + private final GroupTypeOperation groupTypeOperation; + private final TitanDao titanDao; + private final UserValidations userValidations; + + public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations) { + this.groupTypeOperation = groupTypeOperation; + this.titanDao = titanDao; + this.userValidations = userValidations; + } + + + public List getAllGroupTypes(String userId, String internalComponentType) { + try { + userValidations.validateUserExists(userId, "get group types", true) + .left() + .on(this::onUserError); + + Set excludeGroupTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping().get(internalComponentType); + return groupTypeOperation.getAllGroupTypes(excludeGroupTypes); + } finally { + titanDao.commit(); + } + } + + private User onUserError(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java index b3448b27ef..5cdb589d2a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; @@ -45,104 +38,152 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @Component("groupTypeImportManager") public class GroupTypeImportManager { - public static void main(String[] args) { - - List properties = new ArrayList<>(); - PropertyDefinition propertyDefintion = new PropertyDefinition(); - propertyDefintion.setName("aaa"); - properties.add(propertyDefintion); - - List allParentsProps = new ArrayList<>(); - allParentsProps.add("aaa"); - allParentsProps.add("bbb"); - - Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); - System.out.println(alreadyExistPropsCollection); - - } - - private static Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class.getName()); - @Resource - private IGroupTypeOperation groupTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Resource - private ToscaOperationFacade toscaOperationFacade; - - @Resource - private CommonImportManager commonImportManager; - - public Either>, ResponseFormat> createGroupTypes(String groupTypesYml) { - return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType); - } - - private Either, ActionStatus> createGroupTypesFromYml(String groupTypesYml) { - - return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData)); - } - - private Either>, ResponseFormat> createGroupTypesByDao(List groupTypesToCreate) { - return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()), - groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), null); - } - - private Either validateGroupType(GroupTypeDefinition groupType) { - Either result = Either.left(ActionStatus.OK); - if (groupType.getMembers() != null) { - if (groupType.getMembers().isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType()); - result = Either.right(responseFormat); - } else { - for (String member : groupType.getMembers()) { - // Verify that such Resource exist - Either eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); - if (eitherMemberExist.isRight()) { - StorageOperationStatus operationStatus = eitherMemberExist.right().value(); - log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); - ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member); - result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member)); - break; - } - } - - } - } - return result; - } - - private GroupTypeDefinition createGroupType(String groupTypeName, Map toscaJson) { - - GroupTypeDefinition groupType = new GroupTypeDefinition(); - - if (toscaJson != null) { - // Description - final Consumer descriptionSetter = description -> groupType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer derivedFromSetter = derivedFrom -> groupType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> groupType.setProperties(values)); - // Metadata - final Consumer> metadataSetter = metadata -> groupType.setMetadata(metadata); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); - // Members - final Consumer> membersSetter = members -> groupType.setMembers(members); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), membersSetter); - - groupType.setType(groupTypeName); - - groupType.setHighestVersion(true); - - groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); - } - return groupType; - } + public static void main(String[] args) { + + List properties = new ArrayList<>(); + PropertyDefinition propertyDefintion = new PropertyDefinition(); + propertyDefintion.setName("aaa"); + properties.add(propertyDefintion); + + List allParentsProps = new ArrayList<>(); + allParentsProps.add("aaa"); + allParentsProps.add("bbb"); + + Set alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet()); + System.out.println(alreadyExistPropsCollection); + + } + + private static final Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class); + @Resource + private IGroupTypeOperation groupTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Resource + private ToscaOperationFacade toscaOperationFacade; + + @Resource + private CommonImportManager commonImportManager; + + public Either>, ResponseFormat> createGroupTypes(String groupTypesYml) { + return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType); + } + + private Either, ActionStatus> createGroupTypesFromYml(String groupTypesYml) { + + return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData)); + } + + private Either>, ResponseFormat> createGroupTypesByDao(List groupTypesToCreate) { + return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()), + groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), groupTypeOperation::upgradeGroupType); + } + + private Either validateGroupType(GroupTypeDefinition groupType) { + Either result = Either.left(ActionStatus.OK); + if (groupType.getMembers() != null) { + if (groupType.getMembers().isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType()); + result = Either.right(responseFormat); + } else { + for (String member : groupType.getMembers()) { + // Verify that such Resource exist + Either eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member); + if (eitherMemberExist.isRight()) { + StorageOperationStatus operationStatus = eitherMemberExist.right().value(); + log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus); + ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member); + result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member)); + break; + } + } + + } + } + return result; + } + + private GroupTypeDefinition createGroupType(String groupTypeName, Map toscaJson) { + + GroupTypeDefinition groupType = new GroupTypeDefinition(); + + if (toscaJson != null) { + // Description + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription); + // Derived From + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), groupType::setDerivedFrom); + // Properties + commonImportManager.setProperties(toscaJson, groupType::setProperties); + // Metadata + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), groupType::setMetadata); + // Capabilities + List capabilityTypes = createGroupCapabilityTypes(toscaJson); + groupType.setCapabilityTypes(capabilityTypes); + // Members + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers); + + groupType.setType(groupTypeName); + + groupType.setHighestVersion(true); + + groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); + } + return groupType; + } + + /** + * @param toscaJson + * @return + */ + private List createGroupCapabilityTypes(Map toscaJson) { + CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder(); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson); + List capabilityTypes; + if (capabilityTypeToscaJsonHolder.isEmpty()) { + capabilityTypes = Collections.emptyList(); + } + else { + capabilityTypes = commonImportManager.createElementTypesFromToscaJsonMap(this::createGroupCapabilityType, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson()); + } + return capabilityTypes; + } + + private class CapabilityTypeToscaJsonHolder { + private Map capabilityTypeToscaJson; + + public Map getCapabilityTypeToscaJson() { + return capabilityTypeToscaJson; + } + + public boolean isEmpty() { + return capabilityTypeToscaJson == null; + } + + public void setCapabilityTypeToscaJson(Map capabilityTypeToscaJson) { + this.capabilityTypeToscaJson = capabilityTypeToscaJson; + } + } + + private CapabilityTypeDefinition createGroupCapabilityType(String capabilityTypeName, Map toscaJson) { + CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition(); + + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capabilityType::setType); + // Properties + commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties); + + return capabilityType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java deleted file mode 100644 index eff3d39f7f..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java +++ /dev/null @@ -1,526 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.impl; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.annotation.Resource; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth; -import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; -import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.util.HealthCheckUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Component("healthCheckBusinessLogic") -public class HealthCheckBusinessLogic { - - protected static String BE_HEALTH_LOG_CONTEXT = "be.healthcheck"; - - private static Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT); - - private static final String BE_HEALTH_CHECK_STR = "beHealthCheck"; - private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s"; - - @Resource - private TitanGenericDao titanGenericDao; - - @Resource - private IEsHealthCheckDao esHealthCheckDao; - - @Resource - private DistributionEngineClusterHealth distributionEngineClusterHealth; - - @Resource - private CassandraHealthCheck cassandraHealthCheck; - - @Autowired - private SwitchoverDetector switchoverDetector; - - private static Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName()); - - private volatile List prevBeHealthCheckInfos = null; - - public HealthCheckBusinessLogic() { - - } - - private ScheduledFuture scheduledFuture = null; - - ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "BE-Health-Check-Task"); - } - }); - - HealthCheckScheduledTask healthCheckScheduledTask = null; - - @PostConstruct - public void init() { - - prevBeHealthCheckInfos = getBeHealthCheckInfos(); - - log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos); - - healthCheckScheduledTask = new HealthCheckScheduledTask(); - - if (this.scheduledFuture == null) { - this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS); - } - - } - - public boolean isDistributionEngineUp() { - - HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { - return false; - } - return true; - } - - public Pair> getBeHealthCheckInfosStatus() { - - return new ImmutablePair>(getAggregateBeStatus(prevBeHealthCheckInfos), prevBeHealthCheckInfos); - - } - - private Boolean getAggregateBeStatus(List beHealthCheckInfos) { - - Boolean status = true; - - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && !healthCheckInfo.getHealthCheckComponent().equals(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE)) { - status = false; - break; - } - } - return status; - } - - - private List getBeHealthCheckInfos() { - - log.trace("In getBeHealthCheckInfos"); - - List healthCheckInfos = new ArrayList(); - - // BE - getBeHealthCheck(healthCheckInfos); - - // Titan - getTitanHealthCheck(healthCheckInfos); - - // Distribution Engine - getDistributionEngineCheck(healthCheckInfos); - - //Cassandra - getCassandraHealthCheck(healthCheckInfos); - - // Amdocs - getAmdocsHealthCheck(healthCheckInfos); - - //DCAE - getDcaeHealthCheck(healthCheckInfos); - - return healthCheckInfos; - } - - private List getBeHealthCheck(List healthCheckInfos) { - String appVersion = ExternalConfiguration.getAppVersion(); - String description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.UP, appVersion, description)); - return healthCheckInfos; - } - - //Removed from aggregate HC - TDP 293490 - /* private List getEsHealthCheck(List healthCheckInfos) { - - // ES health check and version - HealthCheckStatus healthCheckStatus; - String description; - - try { - healthCheckStatus = esHealthCheckDao.getClusterHealthStatus(); - } catch (Exception e) { - healthCheckStatus = HealthCheckStatus.DOWN; - description = "ES cluster error: " + e.getMessage(); - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description)); - return healthCheckInfos; - } - if (healthCheckStatus.equals(HealthCheckStatus.DOWN)) { - description = "ES cluster is down"; - } else { - description = "OK"; - } - healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description)); - return healthCheckInfos; - } - */ - public List getTitanHealthCheck(List healthCheckInfos) { - // Titan health check and version - String description; - boolean isTitanUp; - - try { - isTitanUp = titanGenericDao.isGraphOpen(); - } catch (Exception e) { - description = "Titan error: " + e.getMessage(); - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); - return healthCheckInfos; - } - if (isTitanUp) { - description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, description)); - } else { - description = "Titan graph is down"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description)); - } - return healthCheckInfos; - } - - private List getCassandraHealthCheck(List healthCheckInfos) { - - String description; - boolean isCassandraUp; - - try { - isCassandraUp = cassandraHealthCheck.getCassandraStatus(); - } catch (Exception e) { - isCassandraUp = false; - description = "Cassandra error: " + e.getMessage(); - } - if (isCassandraUp) { - description = "OK"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.UP, null, description)); - } else { - description = "Cassandra is down"; - healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.DOWN, null, description)); - } - return healthCheckInfos; - - } - - private void getDistributionEngineCheck(List healthCheckInfos) { - - HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo(); - - healthCheckInfos.add(healthCheckInfo); - - } - - private List getAmdocsHealthCheck(List healthCheckInfos) { - HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()); - healthCheckInfos.add(beHealthCheckInfo); - return healthCheckInfos; - } - - private List getDcaeHealthCheck(List healthCheckInfos) { - HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl()); - healthCheckInfos.add(beHealthCheckInfo); - return healthCheckInfos; - } - - private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) { - HealthCheckStatus healthCheckStatus; - String description; - String version = null; - List componentsInfo = new ArrayList<>(); - - CloseableHttpClient httpClient = getHttpClient(); - - if (healthCheckUrl != null) { - HttpGet httpGet = new HttpGet(healthCheckUrl); - CloseableHttpResponse beResponse; - int beStatus; - try { - beResponse = httpClient.execute(httpGet); - beStatus = beResponse.getStatusLine().getStatusCode(); - - String aggDescription = ""; - - if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) { - HttpEntity entity = beResponse.getEntity(); - String beJsonResponse = EntityUtils.toString(entity); - log.trace("{} Health Check response: {}", componentName, beJsonResponse); - - ObjectMapper mapper = new ObjectMapper(); - Map healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference>(){}); - version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null; - if (healthCheckMap.containsKey("componentsInfo")) { - componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference>() {}); - } - - if (componentsInfo.size() > 0) { - aggDescription = HealthCheckUtil.getAggregateDescription(componentsInfo, null); - } else { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, null)); - } - } else { - log.trace("{} Health Check Response code: {}", componentName, beStatus); - } - - if (beStatus != HttpStatus.SC_OK) { - healthCheckStatus = HealthCheckStatus.DOWN; - description = aggDescription.length() > 0 - ? aggDescription - : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN. - if (componentsInfo.size() == 0) { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - } else { - healthCheckStatus = HealthCheckStatus.UP; - description = "OK"; - } - - } catch (Exception e) { - log.error("{} unexpected response: ", componentName, e); - healthCheckStatus = HealthCheckStatus.DOWN; - description = componentName + " unexpected response: " + e.getMessage(); - if (componentsInfo != null && componentsInfo.size() == 0) { - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (IOException e) { - log.error("closing http client has failed" , e); - } - } - } - } else { - healthCheckStatus = HealthCheckStatus.DOWN; - description = componentName + " health check Configuration is missing"; - componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description)); - } - - return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo); - } - - private CloseableHttpClient getHttpClient() { - int timeout = 3000; - RequestConfig.Builder requestBuilder = RequestConfig.custom(); - requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout); - - HttpClientBuilder builder = HttpClientBuilder.create(); - builder.setDefaultRequestConfig(requestBuilder.build()); - return builder.build(); - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (healthCheckScheduler != null) { - healthCheckScheduler.shutdown(); - } - - } - - public class HealthCheckScheduledTask implements Runnable { - - List healthCheckCalls = new ArrayList<>(); - - public HealthCheckScheduledTask() { - - } - - @Override - public void run() { - - healthLogger.trace("Executing BE Health Check Task"); - - List currentBeHealthCheckInfos = getBeHealthCheckInfos(); - boolean healthStatus = getAggregateBeStatus(currentBeHealthCheckInfos); - - boolean prevHealthStatus = getAggregateBeStatus(prevBeHealthCheckInfos); - - boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos); - - if (prevHealthStatus != healthStatus || anyStatusChanged) { - log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); - - prevBeHealthCheckInfos = currentBeHealthCheckInfos; - logAlarm(healthStatus); - } - - } - } - - private void logAlarm(boolean prevHealthState) { - if (prevHealthState) { - BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR); - } else { - BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR); - } - } - - private void logAlarm(String componentChangedMsg) { - BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg); - } - - - public String getSiteMode() { - return switchoverDetector.getSiteMode(); - } - - public boolean anyStatusChanged(List beHealthCheckInfos, List prevBeHealthCheckInfos) { - - boolean result = false; - - if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) { - - Map currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); - Map prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus())); - - if (currentValues != null && prevValues != null) { - int currentSize = currentValues.size(); - int prevSize = prevValues.size(); - - if (currentSize != prevSize) { - - result = true; //extra/missing component - - Map notPresent = null; - if (currentValues.keySet().containsAll(prevValues.keySet())) { - notPresent = new HashMap<>(currentValues); - notPresent.keySet().removeAll(prevValues.keySet()); - } else { - notPresent = new HashMap<>(prevValues); - notPresent.keySet().removeAll(currentValues.keySet()); - } - - for (String component : notPresent.keySet()) { - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component))); - } - // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next(); - - } else { - - for (Entry entry : currentValues.entrySet()) { - String key = entry.getKey(); - HealthCheckStatus value = entry.getValue(); - - if (!prevValues.containsKey(key)) { - result = true; //component missing - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); - break; - } - - HealthCheckStatus prevHealthCheckStatus = prevValues.get(key); - - if (value != prevHealthCheckStatus) { - result = true; //component status changed - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key))); - break; - } - } - } - } - - } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) { - result = false; - } else { - logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null")); - result = true; - } - - return result; - } - - private String buildOnBoardingHealthCheckUrl() { - - Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); - - if (onboardingConfig != null) { - String protocol = onboardingConfig.getProtocol(); - String host = onboardingConfig.getHost(); - Integer port = onboardingConfig.getPort(); - String uri = onboardingConfig.getHealthCheckUri(); - - return protocol + "://" + host + ":" + port + uri; - } - - log.error("onboarding health check configuration is missing."); - return null; - } - - private String buildDcaeHealthCheckUrl() { - - Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae(); - - if (dcaeConfig != null) { - String protocol = dcaeConfig.getProtocol(); - String host = dcaeConfig.getHost(); - Integer port = dcaeConfig.getPort(); - String uri = dcaeConfig.getHealthCheckUri(); - - return protocol + "://" + host + ":" + port + uri; - } - - log.error("dcae health check configuration is missing."); - return null; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java new file mode 100644 index 0000000000..84df217815 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.common.api.HealthCheckInfo; + +public interface HealthCheckInformer { + + HealthCheckInfo getHealthCheckInfo(); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java index 66c1868223..57e6eb54a7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.be.components.impl; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; public interface IDeploymentArtifactTypeConfigGetter { - ArtifactTypeConfig getDeploymentArtifactConfig(); + ArtifactTypeConfig getDeploymentArtifactConfig(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index 01d64f519f..3db76a9398 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -20,20 +20,10 @@ package org.openecomp.sdc.be.components.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Consumer; -import java.util.function.Function; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.commons.lang3.StringEscapeUtils; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; @@ -45,7 +35,6 @@ import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import org.openecomp.sdc.common.util.GsonFactory; import org.springframework.beans.factory.config.YamlProcessor; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @@ -54,719 +43,607 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.function.Function; public final class ImportUtils { - private ImportUtils() { - - } - - private static CustomResolver customResolver = new CustomResolver(); - private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader(); - - private static class CustomResolver extends Resolver { - @Override - protected void addImplicitResolvers() { - // avoid implicit resolvers for strings that can be interpreted as boolean values - addImplicitResolver(Tag.STR, EMPTY, ""); - addImplicitResolver(Tag.STR, NULL, null); - addImplicitResolver(Tag.NULL, NULL, "~nN\0"); - addImplicitResolver(Tag.NULL, EMPTY, null); - addImplicitResolver(Tag.INT, INT, "-+0123456789"); - addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); - addImplicitResolver(Tag.YAML, YAML, "!&*"); - } - } - - - private static void buildMap(Map output, Map map) { - for (Entry entry : map.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof Map) { - Map result = new LinkedHashMap<>(); - buildMap(result, (Map) value); - output.put(key, result); - } - else if (value instanceof Collection) { - Map result = new LinkedHashMap<>(); - int i = 0; - for(Object item : (Collection) value) { - buildMap(result, Collections.singletonMap("[" + (i++) + "]", item)); - } - output.put(key, new ArrayList<>(result.values())); - } - else { - output.put(key, value); - } - } - } - - public static Map loadYamlAsStrictMap(String content){ - Map result = new LinkedHashMap<>(); - Object map = STRICT_MAPPING_YAML_LOADER.load(content); - buildMap(result, (Map)map); - return result; - } - - private static class YamlLoader extends YamlProcessor { - public Yaml getStrictYamlLoader() { - return createYaml(); - } - } - - @SuppressWarnings("unchecked") - public static Either, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) { - Map heatData = (Map) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); - return getHeatParameters(heatData, artifactType); - } - - public static class Constants { - - public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0"; - public static final String FIRST_NON_CERTIFIED_VERSION = "0.1"; - public static final String VENDOR_NAME = "ATT (Tosca)"; - public static final String VENDOR_RELEASE = "1.0.0.wd03"; - public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED; - public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; - public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true; - // public static final String ABSTRACT_CATEGORY = "Generic/Abstract"; - public static final String ABSTRACT_CATEGORY_NAME = "Generic"; - public static final String ABSTRACT_SUBCATEGORY = "Abstract"; - public static final String DEFAULT_ICON = "defaulticon"; - public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC"; - public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; - public static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_"; - public static final List TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1"); - public static final List TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar"); - public static final String UI_JSON_PAYLOAD_NAME = "payloadName"; - public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF"; - } - - public enum ResultStatusEnum { - ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME - } - - public enum ToscaElementTypeEnum { - BOOLEAN, STRING, MAP, LIST, ALL - } - - public enum ToscaTagNamesEnum { - DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"), - // Properties - PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"), - // Group Types - MEMBERS("members"), METADATA("metadata"), - // Policy Types - TARGETS("targets"), - // Capabilities - CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"), - // Requirements - REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"), - // Heat env Validation - PARAMETERS("parameters"), - // Import Validations - TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"), - SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"), - // Attributes - ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input"); - - private String elementName; - - private ToscaTagNamesEnum(String elementName) { - this.elementName = elementName; - } - - public String getElementName() { - return elementName; - } - } - - @SuppressWarnings("unchecked") - private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List returnedList) { - if (elementValue instanceof Map) { - ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); - } else if (elementValue instanceof List) { - ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); - } - } - - @SuppressWarnings("unchecked") - private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List returnedList, Object elementValue) { - - if (elementValue instanceof Boolean) { - if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - } - - else if (elementValue instanceof String) { - if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - } else if (elementValue instanceof Map) { - if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); - - } else if (elementValue instanceof List) { - if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { - returnedList.add(elementValue); - } - ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); - - } - // For Integer, Double etc... - else if (elementType == ToscaElementTypeEnum.ALL) { - if (elementValue != null) { - returnedList.add(String.valueOf(elementValue)); - } - } - } - - private static void findAllToscaElementsInList(List list, String elementName, ToscaElementTypeEnum elementType, List returnedList) { - Iterator listItr = list.iterator(); - while (listItr.hasNext()) { - Object elementValue = listItr.next(); - handleElementNameNotFound(elementName, elementValue, elementType, returnedList); - } - - } - - public static Either findToscaElement(Map toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { - List foundElements = new ArrayList<>(); - Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); - if (foundElements.size() > 0) { - returnedElement = Either.left(foundElements.get(0)); - } - return returnedElement; - - } - - /** - * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType.
- * Returns Either element with:
- * List with all value if values found
- * Or ELEMENT_NOT_FOUND ActionStatus - * - * @param toscaJson - * @param toscaTagName - * @return - */ - public static Either, ResultStatusEnum> findToscaElements(Map toscaJson, String elementName, ToscaElementTypeEnum elementType, List returnedList) { - Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - String skipKey = null; - if (toscaJson.containsKey(elementName)) { - Object elementValue = toscaJson.get(elementName); - handleElementNameFound(elementName, elementType, returnedList, elementValue); - skipKey = elementName; - } - - Iterator> keyValItr = toscaJson.entrySet().iterator(); - while (keyValItr.hasNext()) { - Entry keyValEntry = keyValItr.next(); - if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) { - handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList); - } - } - - if (returnedList.size() > 0) { - returnedElement = Either.left(returnedList); - } - - return returnedElement; - } - - @SuppressWarnings("unchecked") - public static Either, ResultStatusEnum> findFirstToscaListElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { - Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST); - if (findFirstToscaElement.isLeft()) { - returnedElement = Either.left((List) findFirstToscaElement.left().value()); - } - return returnedElement; - - } - - @SuppressWarnings("unchecked") - public static Either, ResultStatusEnum> findFirstToscaMapElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { - Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP); - if (findFirstToscaElement.isLeft()) { - returnedElement = Either.left((Map) findFirstToscaElement.left().value()); - } - return returnedElement; - - } - - public static Either findFirstToscaStringElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { - Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING); - if (findFirstToscaElements.isLeft()) { - returnedElement = Either.left((String) findFirstToscaElements.left().value()); - } - return returnedElement; - } - - /** - * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status - * - * @param toscaJson - * @param toscaTagName - * @return - */ - public static Either findFirstToscaBooleanElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { - Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN); - if (findFirstToscaElements.isLeft()) { - returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value())); - } - return returnedElement; - } - - private static void setPropertyConstraints(Map propertyValue, PropertyDefinition property) { - Either, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS); - if (propertyFieldconstraints.isLeft()) { - List jsonConstraintList = propertyFieldconstraints.left().value(); - - List constraintList = new ArrayList<>(); - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - for (Object constraintJson : jsonConstraintList) { - PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); - constraintList.add(propertyConstraint); - } - property.setConstraints(constraintList); - } - } - - public static PropertyDefinition createModuleProperty(Map propertyValue) { - - PropertyDefinition propertyDef = new PropertyDefinition(); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type)); - ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc)); - - Either findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (findToscaElement.isLeft()) { - String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType()); - propertyDef.setDefaultValue(propertyJsonStringValue); - } - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); - ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status)); - ImportUtils.setPropertyScheme(propertyValue, propertyDef); - ImportUtils.setPropertyConstraints(propertyValue, propertyDef); - - return propertyDef; - } - - public static InputDefinition createModuleInput(Map inputValue) { - - InputDefinition inputDef = new InputDefinition(); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc)); - - Either findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (findToscaElement.isLeft()) { - String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType()); - inputDef.setDefaultValue(propertyJsonStringValue); - } - ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); - ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); - ImportUtils.setPropertyScheme(inputValue, inputDef); - ImportUtils.setPropertyConstraints(inputValue, inputDef); - - return inputDef; - } - - public static PropertyDefinition createModuleAttribute(Map attributeMap) { - - PropertyDefinition attributeDef = new PropertyDefinition(); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); - ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); - Either eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (eitherDefaultValue.isLeft()) { - String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType()); - attributeDef.setDefaultValue(attributeDefaultValue); - } - Either eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL); - if (eitherValue.isLeft()) { - String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType()); - attributeDef.setValue(attributeValue); - } - ImportUtils.setAttributeScheme(attributeMap, attributeDef); - return attributeDef; - } - - private static void setPropertyFieldStatus(Map propertyValue, PropertyDefinition propertyDef) { - Either propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); - if (propertyFieldIsStatus.isLeft()) { - propertyDef.setStatus(propertyFieldIsStatus.left().value()); - } - - } - - private static void setAttributeFieldStatus(Map propertyValue, PropertyDefinition propertyDef) { - Either propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); - if (propertyFieldIsStatus.isLeft()) { - propertyDef.setStatus(propertyFieldIsStatus.left().value()); - } - - } - - private static void setPropertyScheme(Map propertyValue, PropertyDefinition propertyDefinition) { - Either eitherSchema = getSchema(propertyValue); - if (eitherSchema.isLeft()) { - SchemaDefinition schemaDef = new SchemaDefinition(); - schemaDef.setProperty(eitherSchema.left().value().getProperty()); - propertyDefinition.setSchema(schemaDef); - } - - } - - private static void setAttributeScheme(Map propertyValue, PropertyDefinition propertyDefinition) { - Either eitherSchema = getSchema(propertyValue); - if (eitherSchema.isLeft()) { - SchemaDefinition schemaDef = new SchemaDefinition(); - schemaDef.setProperty(eitherSchema.left().value().getProperty()); - propertyDefinition.setSchema(schemaDef); - } - - } - - private static Either getSchema(Map propertyValue) { - Either result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); - if (propertyFieldEntryScheme.isLeft()) { - if (propertyFieldEntryScheme.left().value() instanceof String) { - String schemaType = (String) propertyFieldEntryScheme.left().value(); - SchemaDefinition schema = new SchemaDefinition(); - PropertyDefinition schemeProperty = new PropertyDefinition(); - schemeProperty.setType(schemaType); - schema.setProperty(schemeProperty); - result = Either.left(schema); - - } else if (propertyFieldEntryScheme.left().value() instanceof Map) { - PropertyDefinition schemeProperty = createModuleProperty((Map) propertyFieldEntryScheme.left().value()); - SchemaDefinition schema = new SchemaDefinition(); - schema.setProperty(schemeProperty); - result = Either.left(schema); - - } - - } - return result; - } - - private static void setPropertyFieldIsPassword(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldIsPassword = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.IS_PASSWORD); - if (propertyFieldIsPassword.isLeft()) { - dataDefinition.setPassword(Boolean.parseBoolean(propertyFieldIsPassword.left().value())); - } - } - - private static ResultStatusEnum setPropertyFieldDefaultValue(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - Gson gson = GsonFactory.getGson(); - if (propertyFieldDefaultValue.isLeft()) { - Object defaultValue = propertyFieldDefaultValue.left().value(); - String type = dataDefinition.getType(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type); - // esofer - supporting customized data types. The validation of the - // type will be in the creation of the property. - // if(innerToscaType == null){ - // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE; - // } - // customized data types value is represented as json. - // Also customized data types which are scalar ones, for example, - // data type which derived from integer, their value will be - // represented as json. - if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) { - String jsonObj = null; - if (defaultValue != null) { - jsonObj = gson.toJson(defaultValue); - } - - dataDefinition.setDefaultValue(jsonObj); - } else { - dataDefinition.setDefaultValue(String.valueOf(defaultValue)); - } - - } - - return ResultStatusEnum.OK; - } - - private static ResultStatusEnum setAttributeFieldDefaultValue(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - Gson gson = GsonFactory.getGson(); - if (propertyFieldDefaultValue.isLeft()) { - Object defaultValue = propertyFieldDefaultValue.left().value(); - String type = dataDefinition.getType(); - ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type); - // esofer - supporting customized data types. The validation of the - // type will be in the creation of the property. - // if(innerToscaType == null){ - // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE; - // } - // customized data types value is represented as json. - // Also customized data types which are scalar ones, for example, - // data type which derived from integer, their value will be - // represented as json. - if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) { - String jsonObj = null; - if (defaultValue != null) { - jsonObj = gson.toJson(defaultValue); - } - - dataDefinition.setDefaultValue(jsonObj); - } else { - dataDefinition.setDefaultValue(String.valueOf(defaultValue)); - } - - } - - return ResultStatusEnum.OK; - } - - public static void setField(Map toscaJson, ToscaTagNamesEnum tagName, Consumer setter) { - Either fieldStringValue = findFirstToscaStringElement(toscaJson, tagName); - if (fieldStringValue.isLeft()) { - setter.accept(fieldStringValue.left().value()); - } - - } - - private static void setPropertyFieldDescription(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - dataDefinition.setDescription(propertyFieldDescription.left().value()); - } - } - - private static void setPropertyFieldRequired(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED); - if (propertyFieldRequired.isLeft()) { - dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value())); - } - } - - private static void setAttributeFieldType(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - dataDefinition.setType(propertyFieldType.left().value()); - } - } - - private static void setPropertyFieldType(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - dataDefinition.setType(propertyFieldType.left().value()); - } - } - - private static void setAttributeFieldDescription(Map propertyValue, PropertyDefinition dataDefinition) { - Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - dataDefinition.setDescription(propertyFieldDescription.left().value()); - } - } - - public static Either, ResultStatusEnum> getProperties(Map toscaJson) { - Function elementGenByName = elementName -> createProperties(elementName); - Function, PropertyDefinition> func = map -> createModuleProperty(map); - - return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func); - - } - - public static Either, ResultStatusEnum> getInputs(Map toscaJson) { - Function elementGenByName = elementName -> createInputs(elementName); - Function, InputDefinition> func = map -> createModuleInput(map); - - return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func); - - } - - public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { - Function elementGenByName = elementName -> createAttribute(elementName); - Function, PropertyDefinition> func = map -> createModuleAttribute(map); - - return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); - } - - public static Either, ResultStatusEnum> getElements(Map toscaJson, ToscaTagNamesEnum elementTagName, Function elementGenByName, - Function, ElementDefinition> func) { - Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); - if (toscaAttributes.isLeft()) { - Map jsonAttributes = toscaAttributes.left().value(); - Map moduleAttributes = new HashMap<>(); - Iterator> propertiesNameValue = jsonAttributes.entrySet().iterator(); - while (propertiesNameValue.hasNext()) { - Entry attributeNameValue = propertiesNameValue.next(); - if (attributeNameValue.getValue() instanceof Map) { - @SuppressWarnings("unchecked") - ElementDefinition attribute = func.apply((Map) attributeNameValue.getValue()); - moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); - } else { - - ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue())); - - moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element); - } - - } - - if (moduleAttributes.size() > 0) { - eitherResult = Either.left(moduleAttributes); - } - - } - return eitherResult; - - } - - private static PropertyDefinition createAttribute(String name) { - PropertyDefinition attribute = new PropertyDefinition(); - - attribute.setName(name); - return attribute; - } - - private static PropertyDefinition createProperties(String name) { - PropertyDefinition property = new PropertyDefinition(); - property.setDefaultValue(name); - property.setName(name); - return property; - } - - private static InputDefinition createInputs(String name) { - InputDefinition input = new InputDefinition(); - - input.setName(name); - return input; - } - - public static Either, ResultStatusEnum> getHeatParameters(Map heatData, String artifactType) { - - Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS); - if (toscaProperties.isLeft()) { - Map jsonProperties = toscaProperties.left().value(); - List moduleProperties = new ArrayList<>(); - Iterator> propertiesNameValue = jsonProperties.entrySet().iterator(); - while (propertiesNameValue.hasNext()) { - Entry propertyNameValue = propertiesNameValue.next(); - if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) { - if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - @SuppressWarnings("unchecked") - Either propertyStatus = createModuleHeatParameter((Map) propertyNameValue.getValue()); - if (propertyStatus.isRight()) { - return Either.right(propertyStatus.right().value()); - } - HeatParameterDefinition property = propertyStatus.left().value(); - property.setName(String.valueOf(propertyNameValue.getKey())); - moduleProperties.add(property); - } else { - addHeatParamDefinition(moduleProperties, propertyNameValue, true); - } - } else { - addHeatParamDefinition(moduleProperties, propertyNameValue, false); - } - - } - - if (moduleProperties.size() > 0) { - eitherResult = Either.left(moduleProperties); - } - - } - return eitherResult; - - } - - private static void addHeatParamDefinition(List moduleProperties, Entry propertyNameValue, boolean isJson) { - HeatParameterDefinition property = new HeatParameterDefinition(); - Object value = propertyNameValue.getValue(); - if (value != null) { - property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value))); - } - property.setName(String.valueOf(propertyNameValue.getKey())); - moduleProperties.add(property); - } - - private static Either createModuleHeatParameter(Map propertyValue) { - HeatParameterDefinition propertyDef = new HeatParameterDefinition(); - String type; - Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); - if (propertyFieldType.isLeft()) { - type = propertyFieldType.left().value(); - propertyDef.setType(type); - } else { - return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE); - } - Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); - if (propertyFieldDescription.isLeft()) { - propertyDef.setDescription(propertyFieldDescription.left().value()); - } - - Either propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); - if (propertyFieldDefaultVal.isLeft()) { - if (propertyFieldDefaultVal.left().value() == null) { - return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE); - } - Object value = propertyFieldDefaultVal.left().value(); - String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)); - propertyDef.setDefaultValue(defaultValue); - propertyDef.setCurrentValue(defaultValue); - } - - return Either.left(propertyDef); - } - - public static String getPropertyJsonStringValue(Object value, String type) { - Gson gson = new Gson(); - if (type == null) { - return null; - } - ToscaPropertyType validType = ToscaPropertyType.isValidType(type); - if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { - return gson.toJson(value); - } - return value.toString(); - } - - /** - * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson - * - * @param toscaJson - * @param elementName - */ - public static void removeElementFromJsonMap(Map toscaJson, String elementName) { - for (Entry entry : toscaJson.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (key.equals(elementName)) { - toscaJson.remove(elementName); - return; - } else if (value instanceof Map) { - removeElementFromJsonMap((Map) value, elementName); - } - } - } + private ImportUtils() { + + } + + private static CustomResolver customResolver = new CustomResolver(); + private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader(); + + private static class CustomResolver extends Resolver { + @Override + protected void addImplicitResolvers() { + // avoid implicit resolvers for strings that can be interpreted as boolean values + addImplicitResolver(Tag.STR, EMPTY, ""); + addImplicitResolver(Tag.STR, NULL, null); + addImplicitResolver(Tag.NULL, NULL, "~nN\0"); + addImplicitResolver(Tag.NULL, EMPTY, null); + addImplicitResolver(Tag.INT, INT, "-+0123456789"); + addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); + addImplicitResolver(Tag.YAML, YAML, "!&*"); + } + } + + + private static void buildMap(Map output, Map map) { + for (Entry entry : map.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof Map) { + Map result = new LinkedHashMap<>(); + buildMap(result, (Map) value); + output.put(key, result); + } + else if (value instanceof Collection) { + Map result = new LinkedHashMap<>(); + int i = 0; + for(Object item : (Collection) value) { + buildMap(result, Collections.singletonMap("[" + (i++) + "]", item)); + } + output.put(key, new ArrayList<>(result.values())); + } + else { + output.put(key, value); + } + } + } + + public static Map loadYamlAsStrictMap(String content){ + Map result = new LinkedHashMap<>(); + Object map = STRICT_MAPPING_YAML_LOADER.load(content); + buildMap(result, (Map)map); + return result; + } + + private static class YamlLoader extends YamlProcessor { + public Yaml getStrictYamlLoader() { + return createYaml(); + } + } + + @SuppressWarnings("unchecked") + public static Either, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) { + Map heatData = (Map) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload); + return getHeatParameters(heatData, artifactType); + } + + public static class Constants { + + public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0"; + public static final String FIRST_NON_CERTIFIED_VERSION = "0.1"; + public static final String VENDOR_NAME = "ATT (Tosca)"; + public static final String VENDOR_RELEASE = "1.0.0.wd03"; + public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED; + public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; + public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true; + public static final String ABSTRACT_CATEGORY_NAME = "Generic"; + public static final String ABSTRACT_SUBCATEGORY = "Abstract"; + public static final String DEFAULT_ICON = "defaulticon"; + public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC"; + public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; + public static final String UI_JSON_PAYLOAD_NAME = "payloadName"; + public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF"; + } + + public enum ResultStatusEnum { + ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME + } + + public enum ToscaElementTypeEnum { + BOOLEAN, STRING, MAP, LIST, ALL + } + + public enum ToscaTagNamesEnum { + DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"), + // Properties + PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"), + // Group Types + MEMBERS("members"), METADATA("metadata"), + // Policy Types + TARGETS("targets"), + // Capabilities + CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"), + // Requirements + REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"), + // Heat env Validation + PARAMETERS("parameters"), + // Import Validations + TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"), + SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"), + // Attributes + ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input"); + + private String elementName; + + private ToscaTagNamesEnum(String elementName) { + this.elementName = elementName; + } + + public String getElementName() { + return elementName; + } + } + + @SuppressWarnings("unchecked") + private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List returnedList) { + if (elementValue instanceof Map) { + ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); + } else if (elementValue instanceof List) { + ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); + } + } + + @SuppressWarnings("unchecked") + private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List returnedList, Object elementValue) { + + if (elementValue instanceof Boolean) { + if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + } + + else if (elementValue instanceof String) { + if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + } else if (elementValue instanceof Map) { + if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); + + } else if (elementValue instanceof List) { + if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { + returnedList.add(elementValue); + } + ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); + + } + // For Integer, Double etc... + else if (elementType == ToscaElementTypeEnum.ALL) { + if (elementValue != null) { + returnedList.add(String.valueOf(elementValue)); + } + } + } + + private static void findAllToscaElementsInList(List list, String elementName, ToscaElementTypeEnum elementType, List returnedList) { + Iterator listItr = list.iterator(); + while (listItr.hasNext()) { + Object elementValue = listItr.next(); + handleElementNameNotFound(elementName, elementValue, elementType, returnedList); + } + + } + + public static Either findToscaElement(Map toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { + List foundElements = new ArrayList<>(); + Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); + if (foundElements.size() > 0) { + returnedElement = Either.left(foundElements.get(0)); + } + return returnedElement; + + } + + /** + * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType.
+ * Returns Either element with:
+ * List with all value if values found
+ * Or ELEMENT_NOT_FOUND ActionStatus + * + * @param toscaJson + * @param toscaTagName + * @return + */ + public static Either, ResultStatusEnum> findToscaElements(Map toscaJson, String elementName, ToscaElementTypeEnum elementType, List returnedList) { + Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + String skipKey = null; + if (toscaJson.containsKey(elementName)) { + Object elementValue = toscaJson.get(elementName); + handleElementNameFound(elementName, elementType, returnedList, elementValue); + skipKey = elementName; + } + + Iterator> keyValItr = toscaJson.entrySet().iterator(); + while (keyValItr.hasNext()) { + Entry keyValEntry = keyValItr.next(); + if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) { + handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList); + } + } + + if (returnedList.size() > 0) { + returnedElement = Either.left(returnedList); + } + + return returnedElement; + } + + @SuppressWarnings("unchecked") + public static Either, ResultStatusEnum> findFirstToscaListElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { + Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST); + if (findFirstToscaElement.isLeft()) { + returnedElement = Either.left((List) findFirstToscaElement.left().value()); + } + return returnedElement; + + } + + @SuppressWarnings("unchecked") + public static Either, ResultStatusEnum> findFirstToscaMapElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { + Either, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP); + if (findFirstToscaElement.isLeft()) { + returnedElement = Either.left((Map) findFirstToscaElement.left().value()); + } + return returnedElement; + + } + + public static Either findFirstToscaStringElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { + Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING); + if (findFirstToscaElements.isLeft()) { + returnedElement = Either.left((String) findFirstToscaElements.left().value()); + } + return returnedElement; + } + + /** + * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status + * + * @param toscaJson + * @param toscaTagName + * @return + */ + public static Either findFirstToscaBooleanElement(Map toscaJson, ToscaTagNamesEnum toscaTagName) { + Either returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN); + if (findFirstToscaElements.isLeft()) { + returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value())); + } + return returnedElement; + } + + private static void setPropertyConstraints(Map propertyValue, PropertyDefinition property) { + Either, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS); + if (propertyFieldconstraints.isLeft()) { + List jsonConstraintList = propertyFieldconstraints.left().value(); + + List constraintList = new ArrayList<>(); + Type constraintType = new TypeToken() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + for (Object constraintJson : jsonConstraintList) { + PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType); + constraintList.add(propertyConstraint); + } + property.setConstraints(constraintList); + } + } + + public static PropertyDefinition createModuleProperty(Map propertyValue) { + + PropertyDefinition propertyDef = new PropertyDefinition(); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type)); + ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc)); + + Either findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (findToscaElement.isLeft()) { + String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType()); + propertyDef.setDefaultValue(propertyJsonStringValue); + } + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass))); + ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status)); + ImportUtils.setPropertyScheme(propertyValue, propertyDef); + ImportUtils.setPropertyConstraints(propertyValue, propertyDef); + + return propertyDef; + } + + public static InputDefinition createModuleInput(Map inputValue) { + + InputDefinition inputDef = new InputDefinition(); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc)); + + Either findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (findToscaElement.isLeft()) { + String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType()); + inputDef.setDefaultValue(propertyJsonStringValue); + } + ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); + ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label)); + ImportUtils.setPropertyScheme(inputValue, inputDef); + ImportUtils.setPropertyConstraints(inputValue, inputDef); + + return inputDef; + } + + public static PropertyDefinition createModuleAttribute(Map attributeMap) { + + PropertyDefinition attributeDef = new PropertyDefinition(); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); + ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); + Either eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (eitherDefaultValue.isLeft()) { + String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType()); + attributeDef.setDefaultValue(attributeDefaultValue); + } + Either eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL); + if (eitherValue.isLeft()) { + String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType()); + attributeDef.setValue(attributeValue); + } + ImportUtils.setAttributeScheme(attributeMap, attributeDef); + return attributeDef; + } + + private static void setPropertyScheme(Map propertyValue, PropertyDefinition propertyDefinition) { + Either eitherSchema = getSchema(propertyValue); + if (eitherSchema.isLeft()) { + SchemaDefinition schemaDef = new SchemaDefinition(); + schemaDef.setProperty(eitherSchema.left().value().getProperty()); + propertyDefinition.setSchema(schemaDef); + } + + } + + private static void setAttributeScheme(Map propertyValue, PropertyDefinition propertyDefinition) { + Either eitherSchema = getSchema(propertyValue); + if (eitherSchema.isLeft()) { + SchemaDefinition schemaDef = new SchemaDefinition(); + schemaDef.setProperty(eitherSchema.left().value().getProperty()); + propertyDefinition.setSchema(schemaDef); + } + + } + + private static Either getSchema(Map propertyValue) { + Either result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); + if (propertyFieldEntryScheme.isLeft()) { + if (propertyFieldEntryScheme.left().value() instanceof String) { + String schemaType = (String) propertyFieldEntryScheme.left().value(); + SchemaDefinition schema = new SchemaDefinition(); + PropertyDefinition schemeProperty = new PropertyDefinition(); + schemeProperty.setType(schemaType); + schema.setProperty(schemeProperty); + result = Either.left(schema); + + } else if (propertyFieldEntryScheme.left().value() instanceof Map) { + PropertyDefinition schemeProperty = createModuleProperty((Map) propertyFieldEntryScheme.left().value()); + SchemaDefinition schema = new SchemaDefinition(); + schema.setProperty(schemeProperty); + result = Either.left(schema); + + } + + } + return result; + } + + public static void setField(Map toscaJson, ToscaTagNamesEnum tagName, Consumer setter) { + Either fieldStringValue = findFirstToscaStringElement(toscaJson, tagName); + if (fieldStringValue.isLeft()) { + setter.accept(fieldStringValue.left().value()); + } + + } + + private static void setPropertyFieldRequired(Map propertyValue, PropertyDefinition dataDefinition) { + Either propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED); + if (propertyFieldRequired.isLeft()) { + dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value())); + } + } + + public static Either, ResultStatusEnum> getProperties(Map toscaJson) { + Function elementGenByName = elementName -> createProperties(elementName); + Function, PropertyDefinition> func = map -> createModuleProperty(map); + + return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func); + + } + + public static Either, ResultStatusEnum> getInputs(Map toscaJson) { + Function elementGenByName = elementName -> createInputs(elementName); + Function, InputDefinition> func = map -> createModuleInput(map); + + return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func); + + } + + public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { + Function elementGenByName = elementName -> createAttribute(elementName); + Function, PropertyDefinition> func = map -> createModuleAttribute(map); + + return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); + } + + public static Either, ResultStatusEnum> getElements(Map toscaJson, ToscaTagNamesEnum elementTagName, Function elementGenByName, + Function, ElementDefinition> func) { + Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); + if (toscaAttributes.isLeft()) { + Map jsonAttributes = toscaAttributes.left().value(); + Map moduleAttributes = new HashMap<>(); + Iterator> propertiesNameValue = jsonAttributes.entrySet().iterator(); + while (propertiesNameValue.hasNext()) { + Entry attributeNameValue = propertiesNameValue.next(); + if (attributeNameValue.getValue() instanceof Map) { + @SuppressWarnings("unchecked") + ElementDefinition attribute = func.apply((Map) attributeNameValue.getValue()); + moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); + } else { + + ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue())); + + moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element); + } + + } + + if (moduleAttributes.size() > 0) { + eitherResult = Either.left(moduleAttributes); + } + + } + return eitherResult; + + } + + private static PropertyDefinition createAttribute(String name) { + PropertyDefinition attribute = new PropertyDefinition(); + + attribute.setName(name); + return attribute; + } + + private static PropertyDefinition createProperties(String name) { + PropertyDefinition property = new PropertyDefinition(); + property.setDefaultValue(name); + property.setName(name); + return property; + } + + private static InputDefinition createInputs(String name) { + InputDefinition input = new InputDefinition(); + + input.setName(name); + return input; + } + + public static Either, ResultStatusEnum> getHeatParameters(Map heatData, String artifactType) { + + Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); + Either, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS); + if (toscaProperties.isLeft()) { + Map jsonProperties = toscaProperties.left().value(); + List moduleProperties = new ArrayList<>(); + Iterator> propertiesNameValue = jsonProperties.entrySet().iterator(); + while (propertiesNameValue.hasNext()) { + Entry propertyNameValue = propertiesNameValue.next(); + if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) { + if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + @SuppressWarnings("unchecked") + Either propertyStatus = createModuleHeatParameter((Map) propertyNameValue.getValue()); + if (propertyStatus.isRight()) { + return Either.right(propertyStatus.right().value()); + } + HeatParameterDefinition property = propertyStatus.left().value(); + property.setName(String.valueOf(propertyNameValue.getKey())); + moduleProperties.add(property); + } else { + addHeatParamDefinition(moduleProperties, propertyNameValue, true); + } + } else { + addHeatParamDefinition(moduleProperties, propertyNameValue, false); + } + + } + + if (moduleProperties.size() > 0) { + eitherResult = Either.left(moduleProperties); + } + + } + return eitherResult; + + } + + private static void addHeatParamDefinition(List moduleProperties, Entry propertyNameValue, boolean isJson) { + HeatParameterDefinition property = new HeatParameterDefinition(); + Object value = propertyNameValue.getValue(); + if (value != null) { + property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value))); + } + property.setName(String.valueOf(propertyNameValue.getKey())); + moduleProperties.add(property); + } + + private static Either createModuleHeatParameter(Map propertyValue) { + HeatParameterDefinition propertyDef = new HeatParameterDefinition(); + String type; + Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); + if (propertyFieldType.isLeft()) { + type = propertyFieldType.left().value(); + propertyDef.setType(type); + } else { + return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE); + } + Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); + if (propertyFieldDescription.isLeft()) { + propertyDef.setDescription(propertyFieldDescription.left().value()); + } + + Either propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); + if (propertyFieldDefaultVal.isLeft()) { + if (propertyFieldDefaultVal.left().value() == null) { + return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE); + } + Object value = propertyFieldDefaultVal.left().value(); + String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)); + propertyDef.setDefaultValue(defaultValue); + propertyDef.setCurrentValue(defaultValue); + } + + return Either.left(propertyDef); + } + + public static String getPropertyJsonStringValue(Object value, String type) { + Gson gson = new Gson(); + if (type == null) { + return null; + } + ToscaPropertyType validType = ToscaPropertyType.isValidType(type); + if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) { + return gson.toJson(value); + } + return value.toString(); + } + + /** + * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson + * + * @param toscaJson + * @param elementName + */ + public static void removeElementFromJsonMap(Map toscaJson, String elementName) { + for (Entry entry : toscaJson.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (key.equals(elementName)) { + toscaJson.remove(elementName); + return; + } else if (value instanceof Map) { + removeElementFromJsonMap((Map) value, elementName); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java deleted file mode 100644 index 52dcce9e2e..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.impl; - -//Pavel -//currently NOT IN USE - there are no informational deployed artifacts after US601880 - -@org.springframework.stereotype.Component("informationDeployedArtifactsBusinessLogic") -public class InformationDeployedArtifactsBusinessLogic { - - /* - * private static Logger log = LoggerFactory.getLogger(InformationDeployedArtifactsBusinessLogic.class. getName()); - * - * @javax.annotation.Resource private ArtifactsBusinessLogic artifactBusinessLogic; - * - * public boolean isInformationDeployedArtifact(ArtifactDefinition artifactInfo) { log.debug("checking if artifact {} is informationalDeployable", artifactInfo.getArtifactName()); boolean informationDeployedArtifact = false; Map resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() .getResourceInformationalDeployedArtifacts(); if( resourceInformationalDeployedArtifacts != null && - * resourceInformationalDeployedArtifacts.containsKey(artifactInfo. getArtifactType())){ if( artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL && artifactInfo.checkEsIdExist()){ informationDeployedArtifact = true; - * - * } } String message = (informationDeployedArtifact) ? "artifact {} is informationalDeployable" : "artifact {} is not informationalDeployable"; log.debug(message, artifactInfo.getArtifactName()); return informationDeployedArtifact; } - * - * public Either validateArtifact(boolean isCreate, ArtifactDefinition artifactInfo, Component parent, NodeTypeEnum parentType) { - * - * log.debug("checking if informationalDeployable artifact {} is valid ", artifactInfo.getArtifactName()); Wrapper responseFormatWrapper = new Wrapper(); Map - * resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration(). getResourceInformationalDeployedArtifacts(); - * - * - * artifactBusinessLogic.validateArtifactTypeExists(responseFormatWrapper, artifactInfo); if( responseFormatWrapper.isEmpty() && isCreate ){ artifactBusinessLogic.validateSingleArtifactType(responseFormatWrapper, - * ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parent, parentType); } if( responseFormatWrapper.isEmpty() ){ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType()); - * artifactBusinessLogic.validateFileExtension(responseFormatWrapper, () -> resourceInformationalDeployedArtifacts.get(artifactInfo.getArtifactType() ), artifactInfo, parentType, artifactType); } - * - * if( responseFormatWrapper.isEmpty() ){ validatePayloadContent(responseFormatWrapper, artifactInfo); } - * - * Either response; if( responseFormatWrapper.isEmpty() ){ response = Either.left(true); } else{ response = Either.right(responseFormatWrapper.getInnerElement()); } - * - * String message = (response.isLeft()) ? "informationalDeployable artifact {} is valid" : "informationalDeployable artifact {} is not valid"; log.debug(message, artifactInfo.getArtifactName()); return response; } - * - * private void validatePayloadContent(Wrapper responseFormatWrapper, ArtifactDefinition artifactToVerify) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactToVerify.getArtifactType()); if( artifactType == - * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData )); - * - * boolean isXmlValid = artifactBusinessLogic.isValidXml(xmlToParse.getBytes()); if( !isXmlValid ){ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus. INVALID_XML, - * artifactToVerify.getArtifactType()); responseFormatWrapper.setInnerElement(responseFormat); log.debug("Xml is not valid for artifact : {}", artifactToVerify.getArtifactName()); } } } - * - * - * - * - * public List getInformationalDeployedArtifactsForResourceInstance( ComponentInstance resourceInstance ) { String resourceUid = resourceInstance.getComponentUid(); String resourceName = resourceInstance.getComponentName(); - * return getInformationalDeployedArtifactsForResource(resourceUid, resourceName); } - * - * private List getInformationalDeployedArtifactsForResource( String resourceUid, String resourceName) { List informationalDeployedArtifacts = new ArrayList(); log. - * debug("checking if informationalDeployable artifacts exist for resource {} " , resourceName); Map resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - * .getResourceInformationalDeployedArtifacts(); - * - * - * Either, StorageOperationStatus> eitherArtifacts = artifactBusinessLogic.getArtifacts(resourceUid, NodeTypeEnum.Resource, false, ArtifactGroupTypeEnum.INFORMATIONAL); - * - * if( eitherArtifacts.isLeft() && resourceInformationalDeployedArtifacts != null ){ Predicate predicate = p -> resourceInformationalDeployedArtifacts.containsKey(p.getArtifactType()) && p.checkEsIdExist() && - * p.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL; informationalDeployedArtifacts = eitherArtifacts.left().value().values().stream().filter( predicate ).collect(Collectors.toList()); } - * - * if( informationalDeployedArtifacts.isEmpty() ){ log.debug("no informationalDeployable artifacts exist for resource {} ", resourceName); } else{ log. debug("informationalDeployable artifacts found for resource {} are :{}", resourceName, - * informationalDeployedArtifacts.toString()); } - * - * - * return informationalDeployedArtifacts; } - * - * public List getAllDeployableArtifacts( Resource resource ){ List merged = new ArrayList(); - * - * List deploymentArtifacts = artifactBusinessLogic.getDeploymentArtifacts(resource, NodeTypeEnum.Resource); merged.addAll(deploymentArtifacts); - * - * List informationalDeployedArtifactsForResource = getInformationalDeployedArtifactsForResource( resource.getUniqueId(), resource.getName()); merged.addAll(informationalDeployedArtifactsForResource); - * - * return merged; } - */ -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index a9e7f0b34b..7b51e92ba2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -20,28 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.stream.Collectors; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.json.simple.JSONObject; +import fj.data.Either; +import org.openecomp.sdc.be.components.property.PropertyDecelerationOrchestrator; import org.openecomp.sdc.be.components.validation.ComponentValidations; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -49,1415 +33,651 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; - -import com.google.gson.Gson; -import fj.data.Either; -import jline.internal.Log; +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_INPUT = "CreateInput"; - private static final String UPDATE_INPUT = "UpdateInput"; - - private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName()); - - private static final String GET_INPUT = "get_input"; - - private static final short LOOP_PROTECTION_LEVEL = 10 ; - - private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty"; - private Gson gson = new Gson(); - - - /** - * associate inputs to a given component with paging - * - * @param componentId - * @param userId - * @param fromId - * @param amount - * @return - */ - public Either, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) { - - Either resp = validateUserExists(userId, "get Inputs", false); - - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreInputs(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - List inputs = component.getInputs(); - - return Either.left(inputs); - - } - - public Either, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - - Either resp = validateUserExists(userId, "get Inputs", false); - - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreComponentInstancesInputs(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - - if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){ - ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; - log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - Map> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap()); - return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList())); - } - - /** - * associate properties to a given component instance input - * - * @param instanceId - * @param userId - * @param inputId - * @return - */ - - public Either, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { - Either resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - String parentId = componentId; - org.openecomp.sdc.be.model.Component component = null; - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - - if(!instanceId.equals(inputId)){ - - - Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny(); - if(ciOp.isPresent()){ - parentId = ciOp.get().getComponentUid(); - } - - } - - filters.setIgnoreInputs(false); - - filters.setIgnoreComponentInstancesProperties(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreProperties(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - - Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - return Either.left(getComponentInstancePropertiesByInputId(component, inputId)); - - } - - public Either updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) { - - Either result = null; - org.openecomp.sdc.be.model.Component component = null; - - - try { - Either resp = validateUserExists(userId, "get input", false); - - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreUsers(false); - - Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, UPDATE_INPUT); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); - return result; - } - } - - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map dataTypes = allDataTypes.left().value(); - - Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; - log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - InputDefinition currentInput = op.get(); - - String innerType = null; - String propertyType = currentInput.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = currentInput.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); - } - innerType = propDef.getType(); - } - // Specific Update Logic - - Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value()); - - String newValue = currentInput.getDefaultValue(); - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - currentInput.setDefaultValue(newValue); - currentInput.setOwnerId(userId); - - Either status = toscaOperationFacade.updateInputOfComponent(component, currentInput); - - if(status.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); - return result; - } - - - result = Either.left(status.left().value()); - - return result; - - - }finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - - } - - public Either, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { - Either resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - String parentId = componentId; - org.openecomp.sdc.be.model.Component component = null; - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreProperties(false); - - Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); - - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - component = getComponentEither.left().value(); - - Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - return Either.left(getComponentInstanceInputsByInputId(component, inputId)); - - } - - public Either, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - org.openecomp.sdc.be.model.Component component = null; - - Map> inputsValueToCreateMap = new HashMap<>(); - Map> propertiesToCreateMap = new HashMap<>(); - Map inputsToCreate = new HashMap<>(); - - try { - Either resp = validateUserExists(userId, "get Properties by input", false); - - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreComponentInstancesInputs(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreComponentInstancesProperties(false); - componentParametersView.setIgnoreUsers(false); + private static final String CREATE_INPUT = "CreateInput"; + private static final String UPDATE_INPUT = "UpdateInput"; - Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + private static final Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); + @Inject + private PropertyDecelerationOrchestrator propertyDecelerationOrchestrator; + @Inject + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - if (shouldLockComp) { - Either lockComponent = lockComponent(component, CREATE_INPUT); - if (lockComponent.isRight()) { - result = Either.right(lockComponent.right().value()); - return result; - } - } + /** + * associate inputs to a given component with paging + * + * @param userId + * @param componentId + * @return + */ + public Either, ResponseFormat> getInputs(String userId, String componentId) { - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map dataTypes = allDataTypes.left().value(); - Map origComponentMap = new HashMap<>(); - - - ////////////////////////////////////////////////////////////////////////////////////////////////////// + Either resp = validateUserExists(userId, "get Inputs", false); - List resList = new ArrayList(); - Map> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap(); - List ciList = component.getComponentInstances(); - if (newInputsMap != null && !newInputsMap.isEmpty()) { - - result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsMap, true); - - if (result.isRight()) { - log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value()); - return result; - } - resList = result.left().value(); - - + if (resp.isRight()) { + return Either.right(resp.right().value()); + } - } - Map> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties(); - if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) { + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); - result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsPropsMap, false); + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); - if (result.isRight()) { - log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value()); - return result; - } - resList = result.left().value(); + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + List inputs = component.getInputs(); - } + return Either.left(inputs); - assignOwnerIdToInputs(userId, inputsToCreate); + } - Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId()); - if(assotiateInputsEither.isRight()){ - log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } + public Either, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) { - Either>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId()); - if(assotiatePropsEither.isRight()){ - log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } - - Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(component, inputsValueToCreateMap); - if(addciInputsEither.isRight()){ - log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - return result; - } - - - - - result = Either.left(resList); - return result; - /////////////////////////////////////////////////////////////////////////////////////////// - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - private void assignOwnerIdToInputs(String userId, Map inputsToCreate) { - inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId)); - } - - private StorageOperationStatus addInputsToComponent(String componentId, Map inputsToCreate, Map> inputsValueToCreateMap, Map allDataTypes, List resList, int index, - String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) { - - - Either, ResponseFormat> result; - String innerType = null; - InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get(); - String serviceInputName = compInstname + "_" + input.getName(); - input.setName(serviceInputName); - - JSONObject jobject = new JSONObject(); - jobject.put(GET_INPUT, input.getName()); - - ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null); - - Either validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - - return validatevalueEiter.right().value(); - } - - String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++); - inputValue.setUniqueId(uniqueId); - inputValue.setValue(validatevalueEiter.left().value()); - - - input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName())); - input.setSchema(oldInput.getSchema()); - input.setDefaultValue(oldInput.getDefaultValue()); - input.setConstraints(oldInput.getConstraints()); - input.setDescription(oldInput.getDescription()); - input.setHidden(oldInput.isHidden()); - input.setImmutable(oldInput.isImmutable()); - input.setDefinition(oldInput.isDefinition()); - input.setRequired(oldInput.isRequired()); - input.setOwnerId(null); - input.setParentUniqueId(null); - input.setInstanceUniqueId(compInstId); - inputsToCreate.put(input.getName(), input); - - - - List getInputValues = new ArrayList<>(); - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputId(input.getUniqueId()); - getInputValueDataDefinition.setInputName(input.getName()); - getInputValues.add(getInputValueDataDefinition); - inputValue.setGetInputValues(getInputValues); - - List inputsValueToCreate = null; - - if(inputsValueToCreateMap.containsKey(compInstId)){ - inputsValueToCreate = inputsValueToCreateMap.get(compInstId); - }else{ - inputsValueToCreate = new ArrayList<>(); - } - inputsValueToCreate.add(inputValue); - inputsValueToCreateMap.put(compInstId, inputsValueToCreate); - - - inputsValueToCreate.add(inputValue); - List inputsValue = input.getInputs(); - if(inputsValue == null) - inputsValue = new ArrayList<>(); - inputsValue.add(inputValue); - input.setInputs(inputsValue); + Either resp = validateUserExists(userId, "get Inputs", false); - resList.add(input); - return StorageOperationStatus.OK; - } - - public Either, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List inputsDefinitions, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - org.openecomp.sdc.be.model.Component component = null; - try { - - if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) { - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Either validateUserExists = validateUserExists(userId, CREATE_INPUT, true); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - - Either validateComponent = validateComponentExists(componentId, componentType, null); - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, CREATE_INPUT); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - Map inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o)); - - result = createInputsInGraph(inputs, component); - } - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - public Either, ResponseFormat> createInputsInGraph(Map inputs, org.openecomp.sdc.be.model.Component component) { - - List resList = inputs.values().stream().collect(Collectors.toList()); - Either, ResponseFormat> result = Either.left(resList); - List resourceProperties = component.getInputs(); - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - - Map dataTypes = allDataTypes.left().value(); - - for (Map.Entry inputDefinition : inputs.entrySet()) { - String inputName = inputDefinition.getKey(); - inputDefinition.getValue().setName(inputName); - - Either preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); - if(preparedInputEither.isRight()){ - return Either.right(preparedInputEither.right().value()); - } - - } - if (resourceProperties != null) { - Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); - Either, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); - if(mergeEither.isRight()){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); - } - inputs = mergeEither.left().value(); - } - - Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); - if(assotiateInputsEither.isRight()){ - log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); - } - result = Either.left(assotiateInputsEither.left().value()); - - return result; - } - - - /* Mutates the object - * Tail recurse -> traverse the tosca elements and remove nested empty map properties - * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected - * - * @param toscaElement - expected map of tosca values - * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map. - **/ - private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){ - //region - Stop if map is empty - if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map)) - return toscaElement; - //endregion - //region - Remove empty map entries & return null iff empty map - if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) { - Object ret; - Set keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException - for( Object key : ((Map)toscaElement).keySet() ) { - Object value = ((Map) toscaElement).get(key); - ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel ); - if ( ret == null ) - keysToRemove.add(key); - } - Collection set = ((Map) toscaElement).keySet(); - if (CollectionUtils.isNotEmpty(set)) - set.removeAll(keysToRemove); - - if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check - return null; - } - //endregion - else - return null; - return toscaElement; - } - - //@returns true iff map nested maps are all empty - //ignores other collection objects - private boolean isEmptyNestedMap(Object element){ - boolean isEmpty = true; - if (element != null){ - if ( element instanceof Map ){ - if (MapUtils.isEmpty((Map)element)) - isEmpty = true; - else - { - for( Object key : ((Map)(element)).keySet() ){ - Object value = ((Map)(element)).get(key); - isEmpty &= isEmptyNestedMap( value ); - } - } - } else { - isEmpty = false; - } - } - return isEmpty; - } - - public Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){ - if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){ - if (deepClone){ - if (!(mappedToscaTemplate instanceof HashMap)) - return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() ); - else - mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone(); - } - return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , InputsBusinessLogic.LOOP_PROTECTION_LEVEL ) ); - } - else { - log.debug("mappedToscaTemplate is empty "); - return Either.right("mappedToscaTemplate is empty "); - } - } - - - - /** - * Delete input from service - * - * @param componentType - * @param inputId - * @param component - * @param user - * - * @return - */ - public Either deleteInput(String componentType, String componentId, String userId, String inputId) { - - Either deleteEither = null; - if (log.isDebugEnabled()) - log.debug("Going to delete input id: {}", inputId); - - // Validate user (exists) - Either userEither = validateUserExists(userId, "Delete input", true); - if (userEither.isRight()) { - deleteEither = Either.right(userEither.right().value()); - return deleteEither; - } - - // Get component using componentType, componentId - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - componentParametersView.setIgnoreComponentInstances(false); - componentParametersView.setIgnoreComponentInstancesInputs(false); - componentParametersView.setIgnoreComponentInstancesProperties(false); - componentParametersView.setIgnoreUsers(false); - - Either componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); - if (componentEither.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); - return deleteEither; - } - org.openecomp.sdc.be.model.Component component = componentEither.left().value(); - - // Validate inputId is child of the component - Optional optionalInput = component.getInputs().stream(). - // filter by ID - filter(input -> input.getUniqueId().equals(inputId)). - // Get the input - findAny(); - if (!optionalInput.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); - } - - InputDefinition inputForDelete = optionalInput.get(); - - // Lock component - Either lockResultEither = lockComponent(componentId, component, "deleteInput"); - if (lockResultEither.isRight()) { - ResponseFormat responseFormat = lockResultEither.right().value(); - deleteEither = Either.right(responseFormat); - return deleteEither; - } - - // Delete input operations - try { - StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - List inputsValue= getComponentInstanceInputsByInputId(component, inputId); - - if(inputsValue != null && !inputsValue.isEmpty()){ - for(ComponentInstanceInput inputValue: inputsValue){ - String compInstId = inputValue.getComponentInstanceId(); - prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath()); - - status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - } - - - } - - // US848813 delete service input that relates to VL / CP property - - List propertiesValue = getComponentInstancePropertiesByInputId(component, inputId); - if(propertiesValue != null && !propertiesValue.isEmpty()){ - //propertyList = propertyValueStatus.left().value(); - for(ComponentInstanceProperty propertyValue: propertiesValue){ - - String compInstId = propertyValue.getComponentInstanceId(); - prepareValueBeforeDelete(compInstId, inputForDelete, propertyValue, propertyValue.getPath()); - - status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue); - if(status != StorageOperationStatus.OK){ - log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId); - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); - return deleteEither; - } - - } - } - - - deleteEither = Either.left(inputForDelete); - return deleteEither; - } finally { - if (deleteEither == null || deleteEither.isRight()) { - log.debug("Component id: {} delete input id: {} failed", componentId, inputId); - titanDao.rollback(); - } else { - log.debug("Component id: {} delete input id: {} success", componentId, inputId); - titanDao.commit(); - } - unlockComponent(deleteEither, component); - } - } - - private Either prepareValueBeforeDelete(String compInstId, InputDefinition inputForDelete, PropertyDefinition inputValue, List pathOfComponentInstances) { - Either deleteEither = Either.left(inputForDelete); - String value = inputValue.getValue(); - Map mappedToscaTemplate = (Map) new Yaml().load(value); - - resetInputName(mappedToscaTemplate, inputForDelete.getName()); - - value = ""; - if(!mappedToscaTemplate.isEmpty()){ - Either result = cleanNestedMap(mappedToscaTemplate , true); - Map modifiedMappedToscaTemplate = mappedToscaTemplate; - if (result.isLeft()) - modifiedMappedToscaTemplate = (Map)result.left().value(); - else - Log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation - value = gson.toJson(modifiedMappedToscaTemplate); - } - inputValue.setValue(value); - - - List getInputsValues = inputValue.getGetInputValues(); - if(getInputsValues != null && !getInputsValues.isEmpty()){ - Optional op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny(); - if(op.isPresent()){ - getInputsValues.remove(op.get()); - } - } - inputValue.setGetInputValues(getInputsValues); - - Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue()); - if (findDefaultValue.isRight()) { - deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); - return deleteEither; - - } - String defaultValue = findDefaultValue.left().value(); - inputValue.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - return deleteEither; - } - - private Either prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map dataTypes) { - - - // validate input default values - Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - return Either.right(defaultValuesValidation.right().value()); - } - // convert property - ToscaPropertyType type = getType(newInputDefinition.getType()); - if (type != null) { - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - if (newInputDefinition != null) { - SchemaDefinition schema = newInputDefinition.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (prop != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newInputDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); - newInputDefinition.setDefaultValue(convertedValue); - } - } - } - return Either.left(newInputDefinition); - } - - public boolean isInputExist(List inputs, String resourceUid, String inputName) { - - if (inputs == null) { - return false; - } - - for (InputDefinition propertyDefinition : inputs) { - String parentUniqueId = propertyDefinition.getParentUniqueId(); - String name = propertyDefinition.getName(); - - if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) { - return true; - } - } - - return false; - - } - - - public Either getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { - Either result = null; - try { - - Either resp = validateUserExists(userId, "get Properties by input", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either, StorageOperationStatus> propertiesEitherRes = null; - - ComponentParametersView filters = new ComponentParametersView(); - filters.disableAll(); - filters.setIgnoreComponentInstances(false); - filters.setIgnoreInputs(false); - filters.setIgnoreComponentInstancesInputs(false); - filters.setIgnoreComponentInstancesProperties(false); - filters.setIgnoreProperties(false); - Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); - if(getComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); - Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); - if(!op.isPresent()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); - log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - InputDefinition resObj = op.get(); - - List inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ; - - resObj.setInputs(inputCIInput); - - - List inputProps = getComponentInstancePropertiesByInputId(component, inputId) ; - - resObj.setProperties(inputProps); - - - result = Either.left(resObj); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - } - - private List getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ - List resList = new ArrayList<>(); - Map> ciPropertiesMap = component.getComponentInstancesProperties(); - if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){ - ciPropertiesMap.forEach(new BiConsumer>() { - @Override - public void accept(String s, List ciPropList) { - String ciName = ""; - Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); - if(ciOp.isPresent()) - ciName = ciOp.get().getName(); - if (ciPropList != null && !ciPropList.isEmpty()) { - for(ComponentInstanceProperty prop: ciPropList){ - List inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } - - } - } - } - }); - } - return resList; - - } - - private List getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ - List resList = new ArrayList<>(); - Map> ciInputsMap = component.getComponentInstancesInputs(); - if(ciInputsMap != null && !ciInputsMap.isEmpty()){ - ciInputsMap.forEach(new BiConsumer>() { - @Override - public void accept(String s, List ciPropList) { - String ciName = ""; - Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny(); - if(ciOp.isPresent()) - ciName = ciOp.get().getName(); - if (ciPropList != null && !ciPropList.isEmpty()) { - for(ComponentInstanceInput prop: ciPropList){ - List inputsValues = prop.getGetInputValues(); - if(inputsValues != null && !inputsValues.isEmpty()){ - for(GetInputValueDataDefinition inputData: inputsValues){ - if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){ - prop.setComponentInstanceId(s); - prop.setComponentInstanceName(ciName); - resList.add(prop); - break; - } - } - } - - } - } - } - }); - } - return resList; - - } - - private Either getOriginComponent(ComponentInstance ci, Map origComponentMap){ - Either result = null; - String compInstname = ci.getNormalizedName(); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreInputs(false); - org.openecomp.sdc.be.model.Component origComponent = null; - if(!origComponentMap.containsKey(ci.getComponentUid())){ - Either componentFound = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView); - - if (componentFound.isRight()) { - result = Either.right(componentFound.right().value()); - return result; - } - origComponent = componentFound.left().value(); - origComponentMap.put(origComponent.getUniqueId(), origComponent); - }else{ - origComponent = origComponentMap.get(ci.getComponentUid()); - } - result = Either.left(origComponent); - return result; - } - - - - private Either, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map origComponentMap, Map inputsToCreate, Map> propertiesToCreateMap, Map> inputsValueToCreateMap, Map dataTypes, List resList, Map> newInputsPropsMap, boolean isInputValue) { - List ciList = component.getComponentInstances(); - String componentId = component.getUniqueId(); - for (Entry> entry : newInputsPropsMap.entrySet()) { - String compInstId = entry.getKey(); - List propertiesToCreate = null; - if(propertiesToCreateMap.containsKey(compInstId)){ - propertiesToCreate = propertiesToCreateMap.get(compInstId); - }else{ - propertiesToCreate = new ArrayList<>(); - } - - List inputsValueToCreate = null; - if(propertiesToCreateMap.containsKey(compInstId)){ - inputsValueToCreate = inputsValueToCreateMap.get(compInstId); - }else{ - inputsValueToCreate = new ArrayList<>(); - } - - List properties = entry.getValue(); - - Optional op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny(); - if(!op.isPresent()){ - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - log.debug("Failed to find component instance {} under component {}", compInstId, componentId); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - ComponentInstance ci = op.get(); - String compInstname = ci.getNormalizedName(); - Either origComponentEither = getOriginComponent(ci, origComponentMap); - if(origComponentEither.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value()); - log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - - } - org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value(); - - - //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); - - String inputName = compInstname; - - if (properties != null && !properties.isEmpty()) { - for (ComponentInstancePropInput propInput : properties) { - propInput.setOwnerId(null); - propInput.setParentUniqueId(null); - - Either createInputRes = createInputForComponentInstance(component, ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, inputName, propInput, isInputValue); - - if (createInputRes.isRight()) { - log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value()))); - - } - - resList.add(createInputRes.left().value()); - - } - if(! isInputValue){ - propertiesToCreateMap.put(compInstId, propertiesToCreate); - } - else{ - inputsValueToCreateMap.put(compInstId, inputsValueToCreate); - } - } - - } - return Either.left(resList); - } - - private Either createInputForComponentInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance ci, Map inputsToCreate, List propertiesToCreate, List inputsValueToCreate, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) { - String propertiesName = propInput.getPropertiesName() ; - PropertyDefinition selectedProp = propInput.getInput(); - String[] parsedPropNames = propInput.getParsedPropNames(); - - if(parsedPropNames != null){ - for(String str: parsedPropNames){ - inputName += "_" + str; - } - } else { - inputName += "_" + propInput.getName(); - } - - InputDefinition input = null; - PropertyDefinition prop = propInput; - - if(CollectionUtils.isNotEmpty(propertiesToCreate) && !isInputValue){ - Optional propOpt = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst(); - if(propOpt.isPresent()){ - prop = propOpt.get(); - } - }else{ - if(CollectionUtils.isNotEmpty(inputsValueToCreate) && isInputValue){ - Optional propOpt = inputsValueToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst(); - if(propOpt.isPresent()){ - prop = propOpt.get(); - } - } - } - - boolean complexProperty = false; - if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ - complexProperty = true; - input = new InputDefinition(selectedProp); - }else{ - input = new InputDefinition(prop); - input.setName(inputName + "_" + prop.getName()); - - } - input.setDefaultValue(prop.getValue()); - input.setName(inputName); - input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName())); - input.setInputPath(propertiesName); - input.setInstanceUniqueId(ci.getUniqueId()); - input.setPropertyId(propInput.getUniqueId()); - - JSONObject jobject = new JSONObject(); - - - if(prop.getValue() == null || prop.getValue().isEmpty()){ - if(complexProperty){ - - jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); - prop.setValue(jobject.toJSONString()); - - }else{ - - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - } - - }else{ - - String value = prop.getValue(); - Object objValue = new Yaml().load(value); - if( objValue instanceof Map || objValue instanceof List ){ - if(!complexProperty){ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - - }else{ - Map mappedToscaTemplate = (Map) objValue; - createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); - - String json = gson.toJson(mappedToscaTemplate); - prop.setValue(json); - - } - - }else{ - jobject.put(GET_INPUT, input.getName()); - prop.setValue(jobject.toJSONString()); - - } - - } - - ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(ci.getUniqueId()); - ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(ci.getName()); - - if(CollectionUtils.isEmpty(prop.getGetInputValues())){ - prop.setGetInputValues(new ArrayList<>()); - } - List getInputValues = prop.getGetInputValues(); - - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputId(input.getUniqueId()); - getInputValueDataDefinition.setInputName(input.getName()); - getInputValues.add(getInputValueDataDefinition); - - if(!isInputValue){ - if(!propertiesToCreate.contains(prop)){ - propertiesToCreate.add((ComponentInstanceProperty)prop); - } - - inputsToCreate.put(input.getName(), input); - List propertiesList = input.getProperties(); - if(propertiesList == null) - propertiesList = new ArrayList<>(); // adding the property with the new value for UI - propertiesList.add((ComponentInstanceProperty)prop); - input.setProperties(propertiesList); - }else{ - ComponentInstanceInput inputValue = new ComponentInstanceInput(prop); - if(!inputsValueToCreate.contains(inputValue)){ - inputsValueToCreate.add(inputValue);; - } - - inputsToCreate.put(input.getName(), input); - List inputsValueList = input.getInputs(); - if(inputsValueList == null) - inputsValueList = new ArrayList<>(); // adding the property with the new value for UI - inputsValueList.add(inputValue); - input.setInputs(inputsValueList); - } - - return Either.left(input); - - } - - private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ - - while(i >= 1){ - if( i == parsedPropNames.length -1){ - JSONObject jobProp = new JSONObject(); - jobProp.put(GET_INPUT, inputName); - ooj.put(parsedPropNames[i], jobProp); - i--; - return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); - }else{ - JSONObject res = new JSONObject(); - res.put(parsedPropNames[i], ooj); - i --; - res = createJSONValueForProperty (i, parsedPropNames, res, inputName); - return res; - } - } - - return ooj; - } - - public void resetInputName(Map lhm1, String inputName){ - for (Map.Entry entry : lhm1.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { - value = ""; - lhm1.remove(key); - } else if (value instanceof Map) { - Map subMap = (Map)value; - resetInputName(subMap, inputName); - } else { - continue; - } - - } - } - - private Map createInputValue(Map lhm1, int index, String[] inputNames, String inputName){ - while(index < inputNames.length){ - if(lhm1.containsKey(inputNames[index])){ - Object value = lhm1.get(inputNames[index]); - if (value instanceof Map){ - if(index == inputNames.length -1){ - ((Map) value).put(GET_INPUT, inputName); - return ((Map) value); - - }else{ - index++; - return createInputValue((Map)value, index, inputNames, inputName); - } - }else{ - Map jobProp = new HashMap<>(); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - lhm1.put(inputNames[index], jobProp); - return lhm1; - }else{ - lhm1.put(inputNames[index], jobProp); - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - }else{ - Map jobProp = new HashMap<>(); - lhm1.put(inputNames[index], jobProp); - if(index == inputNames.length -1){ - jobProp.put(GET_INPUT, inputName); - return jobProp; - }else{ - index++; - return createInputValue(jobProp, index, inputNames, inputName); - } - } - } - return lhm1; - } + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreComponentInstancesInputs(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + + if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){ + ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; + log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + Map> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap()); + return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList())); + } + + /** + * associate properties to a given component instance input + * + * @param instanceId + * @param userId + * @param inputId + * @return + */ + + public Either, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) { + Either resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + + if(!instanceId.equals(inputId)){ + + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + Optional ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny(); + if(ciOp.isPresent()){ + parentId = ciOp.get().getComponentUid(); + } + + } + + filters.setIgnoreInputs(false); + + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId)); + + } + + private Either updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map dataTypes) { + String innerType = null; + String propertyType = currentInput.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = currentInput.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE))); + } + innerType = propDef.getType(); + } + // Specific Update Logic + + Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes); + + String newValue = currentInput.getDefaultValue(); + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (Boolean.FALSE.equals(res)) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + return Either.left(newValue); + } + + private InputDefinition getInputFromInputsListById(List componentsOldInputs, InputDefinition input) { + Optional foundInput = componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst(); + return foundInput.isPresent() ? foundInput.get() : null; + } + + public Either, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List inputs, String userId, boolean shouldLockComp, boolean inTransaction) { + + List returnInputs = new ArrayList<>(); + Either, ResponseFormat> result = null; + org.openecomp.sdc.be.model.Component component = null; + + try { + Either resp = validateUserExists(userId, "get input", false); + + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreUsers(false); + + Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + if (shouldLockComp) { + Either lockComponent = lockComponent(component, UPDATE_INPUT); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } + + Either canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + + Map dataTypes = allDataTypes.left().value(); + List componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList()); + for (InputDefinition newInput: inputs) { + InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput); + if (currInput == null) { + ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND; + log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus.name()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + return result; + } + Either updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes); + if ( updateInputObjectValue.isRight()) { + return Either.right(updateInputObjectValue.right().value()); + } + String newValue = updateInputObjectValue.left().value(); + currInput.setDefaultValue(newValue); + currInput.setOwnerId(userId); + Either status = toscaOperationFacade.updateInputOfComponent(component, currInput); + if(status.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value()); + result = Either.right(componentsUtils.getResponseFormat(actionStatus, "")); + return result; + } else { + returnInputs.add(status.left().value()); + } + } + result = Either.left(returnInputs); + return result; + } finally { + if (false == inTransaction) { + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + } + // unlock resource + if (shouldLockComp && component != null) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + } + } + + public Either, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) { + Either resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + String parentId = componentId; + org.openecomp.sdc.be.model.Component component = null; + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreProperties(false); + + Either getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters); + + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + component = getComponentEither.left().value(); + + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId)); + + } + + public Either, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { + + Either, ResponseFormat> result = null; + org.openecomp.sdc.be.model.Component component = null; + + try { + Either resp = validateUserExists(userId, "get Properties by input", false); + + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnoreUsers(false); + + Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + if (shouldLockComp) { + Either lockComponent = lockComponent(component, CREATE_INPUT); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } + + Either canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + + result = propertyDecelerationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi) + .left() + .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)) + .right() + .map(err -> componentsUtils.getResponseFormat(err)); + + return result; + + } finally { + + if (!inTransaction) { + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + } + // unlock resource + if (shouldLockComp && component != null) { + graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); + } + + } + } + + private Either, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List inputsToCreate) { + Map inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName); + assignOwnerIdToInputs(userId, inputsToPersist); + return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId) + .left() + .map(persistedInputs -> inputsToCreate); + } + + private void assignOwnerIdToInputs(String userId, Map inputsToCreate) { + inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId)); + } + + public Either, ResponseFormat> createInputsInGraph(Map inputs, org.openecomp.sdc.be.model.Component component) { + + List resList = inputs.values().stream().collect(Collectors.toList()); + Either, ResponseFormat> result = Either.left(resList); + List resourceProperties = component.getInputs(); + + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + return Either.right(allDataTypes.right().value()); + } + + Map dataTypes = allDataTypes.left().value(); + + for (Map.Entry inputDefinition : inputs.entrySet()) { + String inputName = inputDefinition.getKey(); + inputDefinition.getValue().setName(inputName); + + Either preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes); + if(preparedInputEither.isRight()){ + return Either.right(preparedInputEither.right().value()); + } + + } + if (resourceProperties != null) { + Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); + Either, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); + if(mergeEither.isRight()){ + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); + } + inputs = mergeEither.left().value(); + } + + Either, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId()); + if(assotiateInputsEither.isRight()){ + log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); + } + result = Either.left(assotiateInputsEither.left().value()); + + return result; + } + + /** + * Delete input from service + * + * @param componentId + * @param userId + * + * @param inputId + * @return + */ + public Either deleteInput(String componentId, String userId, String inputId) { + + Either deleteEither = null; + if (log.isDebugEnabled()) + log.debug("Going to delete input id: {}", inputId); + + // Validate user (exists) + Either userEither = validateUserExists(userId, "Delete input", true); + if (userEither.isRight()) { + deleteEither = Either.right(userEither.right().value()); + return deleteEither; + } + + // Get component using componentType, componentId + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreInputs(false); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesInputs(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnorePolicies(false); + componentParametersView.setIgnoreUsers(false); + + Either componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (componentEither.isRight()) { + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value()))); + return deleteEither; + } + org.openecomp.sdc.be.model.Component component = componentEither.left().value(); + + // Validate inputId is child of the component + Optional optionalInput = component.getInputs().stream(). + // filter by ID + filter(input -> input.getUniqueId().equals(inputId)). + // Get the input + findAny(); + if (!optionalInput.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); + } + + InputDefinition inputForDelete = optionalInput.get(); + + // Lock component + Either lockResultEither = lockComponent(componentId, component, "deleteInput"); + if (lockResultEither.isRight()) { + ResponseFormat responseFormat = lockResultEither.right().value(); + deleteEither = Either.right(responseFormat); + return deleteEither; + } + + // Delete input operations + try { + StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); + if (status != StorageOperationStatus.OK) { + log.debug("Component id: {} delete input id: {} failed", componentId, inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + StorageOperationStatus storageOperationStatus = propertyDecelerationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete); + if (storageOperationStatus != StorageOperationStatus.OK) { + log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId); + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName())); + return deleteEither; + } + deleteEither = Either.left(inputForDelete); + return deleteEither; + } finally { + if (deleteEither == null || deleteEither.isRight()) { + log.debug("Component id: {} delete input id: {} failed", componentId, inputId); + titanDao.rollback(); + } else { + log.debug("Component id: {} delete input id: {} success", componentId, inputId); + titanDao.commit(); + } + unlockComponent(deleteEither, component); + } + } + + private Either prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map dataTypes) { + + + // validate input default values + Either defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + return Either.right(defaultValuesValidation.right().value()); + } + // convert property + ToscaPropertyType type = getType(newInputDefinition.getType()); + if (type != null) { + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + if (newInputDefinition != null) { + SchemaDefinition schema = newInputDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newInputDefinition.getDefaultValue() != null) { + convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); + newInputDefinition.setDefaultValue(convertedValue); + } + } + } + return Either.left(newInputDefinition); + } + + public Either getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) { + Either result = null; + try { + + Either resp = validateUserExists(userId, "get Properties by input", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreInputs(false); + filters.setIgnoreComponentInstancesInputs(false); + filters.setIgnoreComponentInstancesProperties(false); + filters.setIgnoreProperties(false); + Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if(getComponentEither.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found component {}, error: {}", componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + org.openecomp.sdc.be.model.Component component = getComponentEither.left().value(); + Optional op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst(); + if(!op.isPresent()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + InputDefinition resObj = op.get(); + + List inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId) ; + + resObj.setInputs(inputCIInput); + + + List inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ; + + resObj.setProperties(inputProps); + + + result = Either.left(resObj); + + return result; + + } finally { + + if (false == inTransaction) { + + if (result == null || result.isRight()) { + log.debug("Going to execute rollback on create group."); + titanDao.rollback(); + } else { + log.debug("Going to execute commit on create group."); + titanDao.commit(); + } + + } + + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java index e7d051290f..cfc2505942 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.InterfaceDefinition; @@ -39,86 +32,86 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; @Component("interfaceLifecycleTypeImportManager") public class InterfaceLifecycleTypeImportManager { - @Resource - private IInterfaceLifecycleOperation interfaceLifecycleOperation; - - @Resource - private ComponentsUtils componentsUtils; - @Resource - private CommonImportManager commonImportManager; - - private static Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class.getName()); - - public Either, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) { - - Either, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml); - if (interfaces.isRight()) { - ActionStatus status = interfaces.right().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null); - return Either.right(responseFormat); - } - return createInterfacesByDao(interfaces.left().value()); - - } - - private Either, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) { - return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData)); - - } - - private Either, ResponseFormat> createInterfacesByDao(List interfacesToCreate) { - List createdInterfaces = new ArrayList<>(); - Either, ResponseFormat> eitherResult = Either.left(createdInterfaces); - Iterator interfaceItr = interfacesToCreate.iterator(); - boolean stopDao = false; - while (interfaceItr.hasNext() && !stopDao) { - InterfaceDefinition interfaceDef = interfaceItr.next(); - - log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType()); - - Either dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef); - if (dataModelResponse.isRight()) { - log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name()); - if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType()); - eitherResult = Either.right(responseFormat); - stopDao = true; - } - - } else { - createdInterfaces.add(dataModelResponse.left().value()); - } - if (!interfaceItr.hasNext()) { - log.info("lifecycle types were created successfully!!!"); - } - } - return eitherResult; - } - - private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map toscaJson) { - InterfaceDefinition interfaceDef = new InterfaceDefinition(); - interfaceDef.setType(interfaceDefinition); - - Map operations = new HashMap(); - - for (Map.Entry entry : toscaJson.entrySet()) { - Operation operation = new Operation(); - Map opProp = (Map) entry.getValue(); - - operation.setDescription((String) opProp.get("description")); - operations.put(entry.getKey(), operation); - } - interfaceDef.setOperationsMap(operations); - return interfaceDef; - } - - public static void setLog(Logger log) { - InterfaceLifecycleTypeImportManager.log = log; - } - + @Resource + private IInterfaceLifecycleOperation interfaceLifecycleOperation; + + @Resource + private ComponentsUtils componentsUtils; + @Resource + private CommonImportManager commonImportManager; + + private static final Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class); + + public Either, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) { + + Either, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml); + if (interfaces.isRight()) { + ActionStatus status = interfaces.right().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null); + return Either.right(responseFormat); + } + return createInterfacesByDao(interfaces.left().value()); + + } + + private Either, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) { + return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData)); + + } + + private Either, ResponseFormat> createInterfacesByDao(List interfacesToCreate) { + List createdInterfaces = new ArrayList<>(); + Either, ResponseFormat> eitherResult = Either.left(createdInterfaces); + Iterator interfaceItr = interfacesToCreate.iterator(); + boolean stopDao = false; + while (interfaceItr.hasNext() && !stopDao) { + InterfaceDefinition interfaceDef = interfaceItr.next(); + + log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType()); + + Either dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef); + if (dataModelResponse.isRight()) { + log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name()); + if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType()); + eitherResult = Either.right(responseFormat); + stopDao = true; + } + + } else { + createdInterfaces.add(dataModelResponse.left().value()); + } + if (!interfaceItr.hasNext()) { + log.info("lifecycle types were created successfully!!!"); + } + } + return eitherResult; + } + + private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map toscaJson) { + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + interfaceDef.setType(interfaceDefinition); + + Map operations = new HashMap(); + + for (Map.Entry entry : toscaJson.entrySet()) { + Operation operation = new Operation(); + Map opProp = (Map) entry.getValue(); + + operation.setDescription((String) opProp.get("description")); + operations.put(entry.getKey(), operation); + } + interfaceDef.setOperationsMap(operations); + return interfaceDef; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java index e9708f50d5..43cf9bdec8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.components.impl; +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.MonitoringDao; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -29,43 +30,41 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component("monitoringBusinessLogic") public class MonitoringBusinessLogic { - private static Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class); - @javax.annotation.Resource - private MonitoringDao monitoringDao; + @javax.annotation.Resource + private MonitoringDao monitoringDao; - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - public Either logMonitoringEvent(MonitoringEvent monitoringEvent) { - if (monitoringDao == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - ActionStatus status = monitoringDao.addRecord(monitoringEvent); - if (!status.equals(ActionStatus.OK)) { - log.warn("Failed to persist monitoring event: {}", status.name()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(true); - } + public Either logMonitoringEvent(MonitoringEvent monitoringEvent) { + if (monitoringDao == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + ActionStatus status = monitoringDao.addRecord(monitoringEvent); + if (!status.equals(ActionStatus.OK)) { + log.warn("Failed to persist monitoring event: {}", status); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(true); + } - public String getEsHost() { + public String getEsHost() { - String res = monitoringDao.getEsHost(); - res = res.replaceAll("[\\[\\]]", ""); - res = res.split(",")[0]; - res = res.replaceAll("[']", ""); - res = res.split(":")[0]; - return res; - } + String res = monitoringDao.getEsHost(); + res = res.replaceAll("[\\[\\]]", ""); + res = res.split(",")[0]; + res = res.replaceAll("[']", ""); + res = res.split(":")[0]; + return res; + } - public String getEsPort() { - return monitoringDao.getEsPort(); - } + public String getEsPort() { + return monitoringDao.getEsPort(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java new file mode 100644 index 0000000000..37a853ccdd --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java @@ -0,0 +1,451 @@ +package org.openecomp.sdc.be.components.impl; + +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +/** + * Provides specified business logic to create, retrieve, update, delete a policy + */ +@org.springframework.stereotype.Component("policyBusinessLogic") +public class PolicyBusinessLogic extends BaseBusinessLogic { + + private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. "; + private static final Logger log = LoggerFactory.getLogger(PolicyBusinessLogic.class); + + /** + * Adds the newly created policy of the specified type to the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyTypeName the name of the policy type + * @param userId the user creator id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + + public Either createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) { + + Either result = null; + log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId); + Wrapper component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return createPolicy(policyTypeName, c); + }); + } catch (Exception e) { + log.error("#createPolicy - the exception occurred upon creation of a policy of the type {} for the component {}: ", policyTypeName, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + + unlockComponent(shouldLock, result, component); + } + return result; + } + + /** + * Retrieves the policy of the component by UniqueId + * + * @param componentType + * @param componentId + * @param policyId + * @param userId + * @return + */ + public Either getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + Either result = null; + log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId); + try { + result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(c -> getPolicyById(c, policyId)); + } catch (Exception e) { + log.error("#getPolicy - the exception occurred upon retrieving the policy {} of the component {}: ", policyId, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return result; + } + + /** + * Updates the policy of the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policy + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + public Either updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) { + Either result = null; + log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId); + Wrapper component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return validateAndUpdatePolicy(c, policy); + }); + } catch (Exception e) { + log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + unlockComponent(shouldLock, result, component); + } + return result; + } + + /** + * Deletes the policy from the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a policy or an error in a response format + */ + public Either deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + Either result = null; + log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); + Wrapper component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) + .left() + .bind(c -> { + component.setInnerElement(c); + return deletePolicy(c, policyId); + }); + } catch (Exception e) { + log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e); + } finally { + unlockComponent(shouldLock, result, component); + } + return result; + } + + public Either updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map> targets, String userId) { + + Either result = null; + log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId); + Component component = null; + + try { + //not right error response + result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true) + .left() + .bind(cmpt -> validateAndUpdatePolicyTargets(cmpt, policyId, targets)); + + return result; + } finally { + + unlockComponentById(result, componentId); + + } + + } + + private Either validateAndUpdatePolicyTargets(Component component, String policyId, Map> targets) { + if (!validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)) { + log.debug("Error finding all the targets: {} .", targets); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, StringUtils.join(targets.values()))); + } + return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId); + + } + + private boolean validateTargetsExistAndTypesCorrect(String componentId, Map> targets) { + Either componentEither = toscaOperationFacade.getToscaFullElement(componentId); + Component parentComponent = componentEither.left().value(); + + return targets.entrySet().stream().noneMatch(t -> checkTargetNotExistOnComponentByType(parentComponent, t)); + } + + private boolean checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry> targetEntry) { + + return targetEntry.getValue().stream() + .anyMatch(id -> checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().toString())); + } + + private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) { + if (type.equalsIgnoreCase(PolicyTargetType.GROUPS.getName()) && parentComponent.getGroups() != null) { + return !parentComponent.getGroupById(uniqueId).isPresent(); + } else if (type.equalsIgnoreCase(PolicyTargetType.COMPONENT_INSTANCES.getName()) && parentComponent.getComponentInstances() != null) { + return !parentComponent.getComponentInstanceById(uniqueId).isPresent(); + } + return true; + } + + private PolicyDefinition setPolicyTargets(PolicyDefinition policyDefinition, Map> targets) { + policyDefinition.setTargets(targets); + return policyDefinition; + } + + + /** + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param userId the user id + * @return a list of policy properties or an error in a response format + */ + public Either, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) { + log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId); + try { + return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(cmpt -> getPolicyById(cmpt, policyId)).left().map(PolicyDataDefinition::getProperties); + } finally { + titanDao.commit(); + } + } + + /** + * Updates the policy properties of the component + * + * @param componentType the type of the component + * @param componentId the id of the component which the policy resides under + * @param policyId the id of the policy which its properties to return + * @param properties a list of policy properties containing updated values + * @param userId the user modifier id + * @param shouldLock the flag defining if the component should be locked + * @return a list of policy properties or anerrorin a response format + */ + public Either, ResponseFormat> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) { + Either, ResponseFormat> result = null; + log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId); + Wrapper component = new Wrapper<>(); + try { + result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left().bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c)); + } catch (Exception e) { + log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (shouldLock && !component.isEmpty()) { + unlockComponent(result, component.getInnerElement()); + } + } + return result; + } + + private Either, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper component, Component c) { + component.setInnerElement(c); + return validateAndUpdatePolicyProperties(c, policyId, properties) + .left() + .map(PolicyDefinition::getProperties); + } + + private void unlockComponent(boolean shouldLock, Either result, Wrapper component) { + if (shouldLock && !component.isEmpty()) { + unlockComponent(result, component.getInnerElement()); + } + } + + private Either getPolicyById(Component component, String policyId) { + PolicyDefinition policyById = component.getPolicyById(policyId); + if (policyById == null) { + String cmptId = component.getUniqueId(); + log.debug("#getPolicyById - policy with id {} does not exist on component with id {}", policyId, cmptId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId)); + } + return Either.left(policyById); + } + + private Either createPolicy(String policyTypeName, Component component) { + return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component)); + } + + private Either addPolicyToComponent(PolicyTypeDefinition policyType, Component component) { + return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies())) + .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) { + return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName) + .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) { + if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component))); + } + return Either.left(policyType); + } + + private String getComponentOrResourceTypeName(Component component) { + return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name(); + } + + private Either validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) { + Wrapper component = new Wrapper<>(); + return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(this::validateComponentIsTopologyTemplate) + .left() + .bind(c -> { + component.setInnerElement(c); + return validateCanWorkOnComponent(c, userId); + }) + .left() + .bind(l -> lockComponent(component.getInnerElement(), shouldLock, "policyWritingOperation")) + .either(l -> Either.left(component.getInnerElement()), r -> { + log.error(FAILED_TO_VALIDATE_COMPONENT, componentId); + return Either.right(r); + }); + } + + private Either validateComponentIsTopologyTemplate(Component component) { + if (!component.isTopologyTemplate()) { + log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", component.getToscaType()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType())); + } + return Either.left(component); + } + + private Either validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) { + Either result = null; + log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId); + Either resp = validateUserExists(userId, "create Policy", false); + if (resp.isRight()) { + log.error("#validateContainerComponentAndUserBeforeReadOperation - failed to validate the user {} before policy processing. ", userId); + result = Either.right(resp.right().value()); + } else { + result = validateComponentExists(componentType, componentId); + if (result.isRight()) { + log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId); + } + return result; + } + return result; + } + + private Either validateComponentExists(ComponentTypeEnum componentType, String componentId) { + + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnorePolicies(false); + filter.setIgnoreUsers(false); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreGroups(false); + return validateComponentExists(componentId, componentType, filter); + } + + + private Either validateAndUpdatePolicy(Component component, PolicyDefinition policy) { + return getPolicyById(component, policy.getUniqueId()) + .left() + .bind(np -> validateUpdatePolicyBeforeUpdate(policy, np, component.getPolicies())) + .left() + .bind(p -> updatePolicyOfComponent(component, p)); + } + + private Either validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) { + return getPolicyById(component, policyId) + .left() + .bind(p -> validateUpdatePolicyPropertiesBeforeUpdate(p, properties)) + .left().bind(l -> updatePolicyOfComponent(component.getUniqueId(), l)); + } + + private Either updatePolicyOfComponent(String componentId, PolicyDefinition policy) { + return toscaOperationFacade.updatePolicyOfComponent(componentId, policy) + .right() + .bind(r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r)))); + } + + private Either validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + if (CollectionUtils.isEmpty(policy.getProperties())) { + log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. "); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); + } + return updatePropertyValues(policy, newProperties); + } + + private Either updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) { + + Map oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity())); + for (PropertyDataDefinition newProperty : newProperties) { + if (!oldProperties.containsKey(newProperty.getName())) { + log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. "); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName())); + } + Either newPropertyValueEither = updatePropertyObjectValue(newProperty, true); + if (newPropertyValueEither.isRight()) { + return Either.right(newPropertyValueEither.right().value()); + } + oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither.left().value()); + } + return Either.left(policy); + } + + private Either deletePolicy(Component component, String policyId) { + return getPolicyById(component, policyId) + .left() + .bind(p -> removePolicyFromComponent(component, p)); + } + + private Either updatePolicyOfComponent(Component component, PolicyDefinition policy) { + Either updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy); + if (updatePolicyRes.isRight()) { + log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value()))); + } else { + log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName()); + return Either.left(updatePolicyRes.left().value()); + } + } + + private Either removePolicyFromComponent(Component component, PolicyDefinition policy) { + StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId()); + if (updatePolicyStatus != StorageOperationStatus.OK) { + log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyStatus))); + } else { + log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus); + return Either.left(policy); + } + } + + private Either validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map policies) { + return validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies) + .right() + .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName()))); + } + + private Either updateTargets(String componentId, PolicyDefinition policy, Map> targets, String policyId) { + if(policy == null){ + return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId)); + } + PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets); + return updatePolicyOfComponent(componentId, updatedPolicy); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java new file mode 100644 index 0000000000..fee8ba187c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java @@ -0,0 +1,56 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +@Component +public class PolicyTypeBusinessLogic { + + private static final Logger log = LoggerFactory.getLogger(PolicyTypeBusinessLogic.class); + private PolicyTypeOperation policyTypeOperation; + private TitanDao titanDao; + private ComponentsUtils componentsUtils; + private UserValidations userValidations; + + public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, TitanDao titanDao, ComponentsUtils componentsUtils, UserValidations userValidations) { + this.policyTypeOperation = policyTypeOperation; + this.titanDao = titanDao; + this.componentsUtils = componentsUtils; + this.userValidations = userValidations; + } + + public Either, ResponseFormat> getAllPolicyTypes(String userId, String internalComponentType) { + try { + Set excludedPolicyTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping().get(internalComponentType); + return userValidations.validateUserExists(userId, "get policy types", true) + .left() + .bind(user -> getPolicyTypes(excludedPolicyTypes)); + } finally { + titanDao.commit(); + } + } + + private Either, ResponseFormat> getPolicyTypes(Set excludedTypes) { + return policyTypeOperation.getAllPolicyTypes(excludedTypes) + .right() + .bind(this::convertToResponseFormatOrNotFoundErrorToEmptyList); + } + + private Either, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus err) { + log.debug("error when trying to fetch policy types: {}", err); + return componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(err); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java index 4a07120994..fed588ff9c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java @@ -20,109 +20,120 @@ package org.openecomp.sdc.be.components.impl; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -import javax.annotation.Resource; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; +import org.openecomp.sdc.be.components.impl.utils.PolicyTypeImportUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; @Component("policyTypeImportManager") public class PolicyTypeImportManager { - @Resource - private IPolicyTypeOperation policyTypeOperation; - @Resource - private ComponentsUtils componentsUtils; - @Autowired - protected IGroupOperation groupOperation; - @Autowired - private ToscaOperationFacade toscaOperationFacade; - - @Resource - private CommonImportManager commonImportManager; - - public Either>, ResponseFormat> createPolicyTypes(String groupTypesYml) { - return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createPolicyTypesFromYml(elementTypeYml), groupTypesList -> createPolicyTypesByDao(groupTypesList), ElementTypeEnum.PolicyType); - } - - private Either, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) { - - return commonImportManager.createElementTypesFromYml(policyTypesYml, (policyTypeName, groupTypeJsonData) -> createPolicyType(policyTypeName, groupTypeJsonData)); - } - - private Either>, ResponseFormat> createPolicyTypesByDao(List policyTypesToCreate) { - return commonImportManager.createElementTypesByDao(policyTypesToCreate, policyType -> validatePolicyType(policyType), policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()), - policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), null); - } - - private Either validatePolicyType(PolicyTypeDefinition policyType) { - Either result = Either.left(ActionStatus.OK); - if (policyType.getTargets() != null) { - if (policyType.getTargets().isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType()); - result = Either.right(responseFormat); - } - if (result.isLeft()) { - for (String targetName : policyType.getTargets()) { - - boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetName).isLeft();; - if (!isValid) { - isValid = groupOperation.isGroupExist(targetName, false); - } - if (!isValid) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetName); - result = Either.right(responseFormat); - break; - } - } - } - } - - return result; - } - - private PolicyTypeDefinition createPolicyType(String groupTypeName, Map toscaJson) { - - PolicyTypeDefinition policyType = new PolicyTypeDefinition(); - - if (toscaJson != null) { - // Description - final Consumer descriptionSetter = description -> policyType.setDescription(description); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); - // Derived From - final Consumer derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); - // Properties - commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values)); - // Metadata - final Consumer> metadataSetter = metadata -> policyType.setMetadata(metadata); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); - // Targets - final Consumer> targetsSetter = targets -> policyType.setTargets(targets); - commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter); - - policyType.setType(groupTypeName); - - policyType.setHighestVersion(true); - - policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); - } - return policyType; - } + @Resource + private IPolicyTypeOperation policyTypeOperation; + @Resource + private ComponentsUtils componentsUtils; + @Autowired + protected IGroupOperation groupOperation; + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Resource + private CommonImportManager commonImportManager; + + public Either>, ResponseFormat> createPolicyTypes(String policyTypesYml) { + return commonImportManager.createElementTypes(policyTypesYml, this::createPolicyTypesFromYml, this::upsertPolicyTypesByDao, ElementTypeEnum.PolicyType); + } + + private Either, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) { + + return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType); + } + + private Either>, ResponseFormat> upsertPolicyTypesByDao(List policyTypesToCreate) { + return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()), + policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), this::updatePolicyType); + } + + private Either updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) { + if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) { + return policyTypeAlreadyExists(); + } + return policyTypeOperation.updatePolicyType(newPolicyType, oldPolicyType); + } + + private Either policyTypeAlreadyExists() { + return Either.right(StorageOperationStatus.OK); + } + + private Either validatePolicyType(PolicyTypeDefinition policyType) { + Either result = Either.left(ActionStatus.OK); + if (policyType.getTargets() != null) { + if (policyType.getTargets().isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType()); + result = Either.right(responseFormat); + } + if (result.isLeft()) { + for (String targetId : policyType.getTargets()) { + boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft(); + if (!isValid) { + isValid = groupOperation.isGroupExist(targetId, false); + } + if (!isValid) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId); + result = Either.right(responseFormat); + break; + } + } + } + } + + + return result; + } + + private PolicyTypeDefinition createPolicyType(String groupTypeName, Map toscaJson) { + + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + + if (toscaJson != null) { + // Description + final Consumer descriptionSetter = description -> policyType.setDescription(description); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter); + // Derived From + final Consumer derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter); + // Properties + commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values)); + // Metadata + final Consumer> metadataSetter = metadata -> policyType.setMetadata(metadata); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter); + // Targets + final Consumer > targetsSetter = targets -> policyType.setTargets(targets); + commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter); + + policyType.setType(groupTypeName); + + policyType.setHighestVersion(true); + + policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION); + } + return policyType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java index da64f3f5b7..ab6ff24676 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -48,846 +41,848 @@ import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("productBusinessLogic") public class ProductBusinessLogic extends ComponentBusinessLogic { - private static final String PRODUCT_FULL_NAME = "full"; - private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated"; - private static Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class.getName()); - private static final String INITIAL_VERSION = "0.1"; - private static List creationRoles; - private static List updateRoles; - private static List contactsRoles; - - public ProductBusinessLogic() { - creationRoles = new ArrayList<>(); - updateRoles = new ArrayList<>(); - contactsRoles = new ArrayList<>(); - - // only PM is allowed to create/update products - creationRoles.add(Role.PRODUCT_MANAGER); - updateRoles.add(Role.PRODUCT_MANAGER); - // Only PM is allowed to be product contacts - contactsRoles.add(Role.PRODUCT_MANAGER); - } - - @Autowired - private IElementOperation elementDao; - - @Autowired - private ProductComponentInstanceBusinessLogic productComponentInstanceBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - public Either createProduct(Product product, User user) { - AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE; - ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; - - // validate user - should be first to get the maximum auditing info in - // case of subsequent failures - log.debug("get user from DB"); - Either eitherCreator = validateUser(user, "Create Product", product, actionEnum, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either validateRes = validateUserRole(user, product, creationRoles, actionEnum, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - if (product == null) { - log.debug("Invalid product json. Check product servlet log for createProduct entry params"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - return Either.right(responseFormat); - } - - // warn about non-updatable fields - checkUnupdatableProductFields(product); - - Either validateProductResponse = validateProductBeforeCreate(product, user, actionEnum); - if (validateProductResponse.isRight()) { - return Either.right(validateProductResponse.right().value()); - } - - log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - Either lockResult = lockComponentByName(product.getSystemName(), product, "Create Product"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult); - - try { - Either createProductEither = toscaOperationFacade.createToscaComponent(product); - - if (createProductEither.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - return Either.right(responseFormat); - } - - log.debug("Product created successfully"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum); - - // //Add product to cache - Product createdProduct = createProductEither.left().value(); - // cacheManagerOperation.updateComponentInCache(createdProduct.getUniqueId(), - // createdProduct.getLastUpdateDate(), NodeTypeEnum.Product); - - return Either.left(createdProduct); - - } finally { - graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product); - } - - } - - private void checkUnupdatableProductFields(Product product) { - checkComponentFieldsForOverrideAttempt(product); - if (product.getNormalizedName() != null) { - log.info("NormalizedName cannot be defined by user. This field will be overridden by the application"); - } - } - - private Either validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) { - - Either validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum); - if (validateProductFields.isRight()) { - return Either.right(validateProductFields.right().value()); - } - - if (product.getIsActive() == null) { - log.debug("no isActive value was provided, setting to default: false"); - product.setIsActive(false); - } - - product.setCreatorUserId(user.getUserId()); - - // enrich object - log.debug("enrich product with version and state"); - product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - product.setVersion(INITIAL_VERSION); - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - product.setInvariantUUID(invariantUUID); - - return Either.left(product); - } - - private Either validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) { - - // To be removed in 1607 - // See below - String oldName = product.getName(); - - Either componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum); - if (componentNameValidation.isRight()) { - return componentNameValidation; - } - - Either componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum); - if (componentNameUniquenessValidation.isRight()) { - return componentNameUniquenessValidation; - } - - // To be removed in 1607 and replaced with generic - // validateTagsListAndRemoveDuplicates() - // See comments on the validateTagsListAndRemoveDuplicates(user, - // product, oldName, actionEnum) function - Either tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum); - if (tagsValidation.isRight()) { - return tagsValidation; - } - - Either validateIconResponse = validateIcon(user, product, actionEnum); - if (validateIconResponse.isRight()) { - return validateIconResponse; - } - - Either projectCodeValidation = validateProjectCode(user, product, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; - } - Either categoryValidation = validateGrouping(user, product, actionEnum); - if (categoryValidation.isRight()) { - return categoryValidation; - } - - Either contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum); - if (contactsListValidation.isRight()) { - return contactsListValidation; - } - - Either productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum); - if (productFullNameValidation.isRight()) { - return productFullNameValidation; - } - - Either descValidation = validateDescriptionAndCleanup(user, product, actionEnum); - if (descValidation.isRight()) { - return descValidation; - } - - return Either.left(true); - } - - public Either, ResponseFormat> validateProductNameExists(String productName, String userId) { - - Either resp = validateUserExists(userId, "validate Product Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - private Either validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) { - List contacts = product.getContacts(); - if (!ValidationUtils.validateListNotEmpty(contacts)) { - log.debug("Contacts list cannot be empty for product {}", product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - boolean isProductCreatorInContacts = false; - String modifierUserId = user.getUserId(); - for (String contact : contacts) { - if (contact.equals(modifierUserId)) { - log.trace("modifier userId found in product contacts"); - isProductCreatorInContacts = true; - // No need to validate for this userId - it's modifier's - continue; - } - if (!ValidationUtils.validateContactId(contact)) { - log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - User contactUser = new User(); - contactUser.setUserId(contact); - Either validateUser = validateUserExists(contact, "Create Product", false); - if (validateUser.isRight()) { - log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - contactUser = validateUser.left().value(); - - Either validateUserRole = validateUserRole(contactUser, contactsRoles); - if (validateUserRole.isRight()) { - log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - } - - if (!isProductCreatorInContacts) { - log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId); - contacts.add(modifierUserId); - } - - // passed - setting all contacts userIds to lowercase - List tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList()); - ValidationUtils.removeDuplicateFromList(tempContacts); - product.setContacts(tempContacts); - - return Either.left(true); - } - - private Either validateGrouping(User user, Product product, AuditingActionEnum actionEnum) { - List categories = product.getCategories(); - if (categories == null || categories.isEmpty()) { - log.debug("Grouping list is empty for product: {}", product.getName()); - return Either.left(true); - } - Map>> nonDuplicatedCategories = new HashMap>>(); - // remove duplicated entries - for (CategoryDefinition cat : categories) { - String catName = cat.getName(); - if (ValidationUtils.validateStringNotEmpty(catName) == false) { - // error missing cat name - log.debug("Missing category name for product: {}", product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - Map> catEntry = nonDuplicatedCategories.get(catName); - if (catEntry == null) { - catEntry = new HashMap>(); - nonDuplicatedCategories.put(catName, catEntry); - } - List subcategories = cat.getSubcategories(); - if (subcategories == null || subcategories.isEmpty()) { - // error missing subcat for cat - log.debug("Missing sub-categories for category {} in product {}", catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - for (SubCategoryDefinition subcat : subcategories) { - String subCatName = subcat.getName(); - if (ValidationUtils.validateStringNotEmpty(subCatName) == false) { - // error missing sub cat name for cat - log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - Set subcatEntry = catEntry.get(subCatName); - if (subcatEntry == null) { - subcatEntry = new HashSet(); - catEntry.put(subCatName, subcatEntry); - } - List groupings = subcat.getGroupings(); - for (GroupingDefinition group : groupings) { - String groupName = group.getName(); - if (ValidationUtils.validateStringNotEmpty(groupName) == false) { - // error missing grouping for sub cat name and cat - log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - if (!subcatEntry.contains(groupName)) { - subcatEntry.add(groupName); - } else { - log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName); - } - } - } - } // for end of checking duplicated - // validate existence - Either, ActionStatus> allProductCategories = elementDao.getAllProductCategories(); - - if (allProductCategories.isRight()) { - log.debug("No product categories {}", allProductCategories.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - boolean catExist; - // convert non-duplicated to data modeling format and update in the - // input object - List newCatList = new ArrayList(); - - // over all categories from request - for (Map.Entry>> entry : nonDuplicatedCategories.entrySet()) { - catExist = false; - CategoryDefinition categoryDefinition = null; - // over all categories from Titan - List categoriesList = allProductCategories.left().value(); - if (categoriesList != null) { - for (CategoryDefinition catInDb : categoriesList) { - if (entry.getKey().equals(catInDb.getName())) { - catExist = true; - boolean subcatExist; - // copy data - categoryDefinition = new CategoryDefinition(catInDb); - SubCategoryDefinition subCategory = null; - - Map> subcats = entry.getValue(); - for (Map.Entry> subcat : subcats.entrySet()) { - subcatExist = false; - List subcategoriesList = catInDb.getSubcategories(); - if (subcategoriesList != null) { - for (SubCategoryDefinition subcatInDb : subcategoriesList) { - if (subcatInDb.getName().equals(subcat.getKey())) { - // copy data - subCategory = new SubCategoryDefinition(subcatInDb); - subcatExist = true; - Set grouping = subcat.getValue(); - boolean groupExist; - GroupingDefinition groupingDefinition = null; - for (String group : grouping) { - groupExist = false; - List groupings = subcatInDb.getGroupings(); - if (groupings != null) { - for (GroupingDefinition groupInDb : groupings) { - if (groupInDb.getName().equals(group)) { - groupExist = true; - groupingDefinition = new GroupingDefinition(groupInDb); - } - } - } - if (!groupExist) { - // error grouping isn't defined - // in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - subCategory.addGrouping(groupingDefinition); - } - } - } - } - if (!subcatExist) { - // error sub category isn't defined in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - categoryDefinition.addSubCategory(subCategory); - } - } - } - } - if (!catExist) { - // error category isn't defined in Titan - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - newCatList.add(categoryDefinition); - } - product.setCategories(newCatList); - return Either.left(true); - } - - public Either getProduct(String productId, User user) { - String ecompErrorContext = "Get product"; - Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either storageStatus = toscaOperationFacade.getToscaElement(productId); - - if (storageStatus.isRight()) { - log.debug("failed to get resource by id {}", productId); - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - // TODO check error - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue())); - } else { - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - } - return Either.left(storageStatus.left().value()); - } - - public Either deleteProduct(String productId, User user) { - String ecompErrorContext = "Delete product"; - Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either storageStatus = toscaOperationFacade.deleteToscaComponent(productId); - - if (storageStatus.isRight()) { - log.debug("failed to delete resource by id {}", productId); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - return Either.left(storageStatus.left().value()); - } - - private Either validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { - String fullName = product.getFullName(); - if (!ValidationUtils.validateStringNotEmpty(fullName)) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(errorResponse, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(errorResponse); - } - - fullName = ValidationUtils.removeNoneUtf8Chars(fullName); - fullName = ValidationUtils.removeHtmlTags(fullName); - fullName = ValidationUtils.normaliseWhitespace(fullName); - fullName = ValidationUtils.stripOctets(fullName); - - if (!ValidationUtils.validateProductFullNameLength(fullName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - if (!ValidationUtils.validateIsEnglish(fullName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - product.setFullName(fullName); - return Either.left(true); - } - - private Either validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { - String name = product.getName(); - if (!ValidationUtils.validateStringNotEmpty(name)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - // Product name is required to have same validation and normalization as - // category - if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name); - - if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - - product.setName(normalizedName4Display); - String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display); - product.setNormalizedName(normalizedName4Uniqueness); - - return Either.left(true); - } - - // This is a workaround for a current tag--->product name behaviour, which - // will be changed in 1607. - // It was agreed with Ella on 23/2/16 that the tag validation of product - // will be made against the old product name (before normalization), - // and in 1607 US will be defined where UI will no longer pass tag of - // component name, and BE will add it by itself after all needed - // normalizations. - private Either validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) { - List tagsList = product.getTags(); - - Either validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT); - if (validateTags.isRight()) { - ResponseFormat responseFormat = validateTags.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT); - return Either.right(responseFormat); - } - ValidationUtils.removeDuplicateFromList(tagsList); - return Either.left(true); - } - - @Override - public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) { - - } - - public Either updateProductMetadata(String productId, Product updatedProduct, User user) { - ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; - Either eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - if (updatedProduct == null) { - log.debug("Invalid product json. Check product servlet log for updateProduct entry params"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - - Either storageStatus = toscaOperationFacade.getToscaElement(productId); - if (storageStatus.isRight()) { - if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); - } - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); - } - - Product currentProduct = storageStatus.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) { - log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct); - if (validationRsponse.isRight()) { - log.info("product update metadata: validations field."); - return validationRsponse; - } - - Product productToUpdate = validationRsponse.left().value(); - // lock resource - Either lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); - if (updateResponse.isRight()) { - toscaOperationFacade.rollback(); - log.debug("failed to update product {}", productToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - toscaOperationFacade.commit(); - return Either.left(updateResponse.left().value()); - } finally { - graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product); - } - } - - private Either validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion()); - Either response = validateAndUpdateProductName(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateFullName(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateCategory(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateContactList(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateTags(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - if (updatedProduct.getIsActive() != null) { - currentProduct.setIsActive(updatedProduct.getIsActive()); - } - - response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String currentInvariantUuid = currentProduct.getInvariantUUID(); - String updatedInvariantUuid = updatedProduct.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Product invariant UUID is automatically set and cannot be updated"); - updatedProduct.setInvariantUUID(currentInvariantUuid); - } - return Either.left(currentProduct); - - } - - private Either validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) { - String updatedProductName = updatedProduct.getName(); - String tags = ""; - String currentProductName = currentProduct.getName(); - if (updatedProductName != null) { - Either validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null); - if (validatProductNameResponse.isRight()) { - ResponseFormat errorRespons = validatProductNameResponse.right().value(); - return Either.right(errorRespons); - } - updatedProductName = updatedProduct.getName(); - if (!currentProductName.equals(updatedProductName)) { - Either productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null); - if (productNameUniquenessValidation.isRight()) { - return productNameUniquenessValidation; - } - currentProduct.setName(updatedProductName); - tags = updatedProductName; - updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName); - currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName)); - List updatedTags = updatedProduct.getTags(); - // As discussed with Ella currently (1604) we are not removing - // the old name from tags. - if (updatedTags == null) { - updatedTags = currentProduct.getTags(); - } - updatedTags.add(tags); - } - } - return Either.left(true); - } - - private Either validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) { - String updatedProductName = updatedProduct.getFullName(); - String currentProductName = currentProduct.getFullName(); - if (updatedProductName != null && !currentProductName.equals(updatedProductName)) { - Either validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null); - if (validatProductNameResponse.isRight()) { - ResponseFormat errorRespons = validatProductNameResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setFullName(updatedProduct.getFullName()); - } - return Either.left(true); - } - - private Either validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { - List categoryUpdated = updatedProduct.getCategories(); - - Either validatCategoryResponse = validateGrouping(user, updatedProduct, null); - if (validatCategoryResponse.isRight()) { - ResponseFormat errorResponse = validatCategoryResponse.right().value(); - return Either.right(errorResponse); - } - - categoryUpdated = updatedProduct.getCategories(); - if (categoryUpdated != null) { - currentProduct.setCategories(categoryUpdated); - } - return Either.left(true); - } - - private Either validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) { - List updatedContacts = updatedProduct.getContacts(); - List currentContacts = currentProduct.getContacts(); - if (updatedContacts != null) { - if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) { - Either validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setContacts(updatedProduct.getContacts()); - } - } - return Either.left(true); - } - - private Either validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) { - List tagsUpdated = updatedProduct.getTags(); - List tagsCurrent = currentProduct.getTags(); - if (tagsUpdated != null) { - if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - Either validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentProduct.setTags(updatedProduct.getTags()); - } - } - return Either.left(true); - } - - @Override - public Either, ResponseFormat> deleteMarkedComponents() { - // markAsDeleted isnt implemented yet - return Either.left(new ArrayList<>()); - } - - @Override - protected boolean validateTagPattern(String tag) { - return ValidationUtils.validateCategoryDisplayNameFormat(tag); - } - - public Either getProductByNameAndVersion(String productName, String productVersion, String userId) { - Either resp = validateUserExists(userId, "get Service By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); - if (storageStatus.isRight()) { - log.debug("failed to get service by name {} and version {}", productName, productVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName)); - } - Product product = storageStatus.left().value(); - return Either.left(product); - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return productComponentInstanceBusinessLogic; - } - - @Override - public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - @Override - public Either getUiComponentDataTransferByComponentId(String componentId, - List dataParamsToReturn) { - // TODO Auto-generated method stub - return null; - } + private static final String PRODUCT_FULL_NAME = "full"; + private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated"; + private static final Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class); + private static final String INITIAL_VERSION = "0.1"; + private static List creationRoles; + private static List updateRoles; + private static List contactsRoles; + + public ProductBusinessLogic() { + creationRoles = new ArrayList<>(); + updateRoles = new ArrayList<>(); + contactsRoles = new ArrayList<>(); + + // only PM is allowed to create/update products + creationRoles.add(Role.PRODUCT_MANAGER); + updateRoles.add(Role.PRODUCT_MANAGER); + // Only PM is allowed to be product contacts + contactsRoles.add(Role.PRODUCT_MANAGER); + } + + @Autowired + private IElementOperation elementDao; + + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + public Either createProduct(Product product, User user) { + AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE; + ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; + + // validate user - should be first to get the maximum auditing info in + // case of subsequent failures + log.debug("get user from DB"); + Either eitherCreator = validateUser(user, "Create Product", product, actionEnum, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, product, creationRoles, actionEnum, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + if (product == null) { + log.debug("Invalid product json. Check product servlet log for createProduct entry params"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + return Either.right(responseFormat); + } + + // warn about non-updatable fields + checkUnupdatableProductFields(product); + + Either validateProductResponse = validateProductBeforeCreate(product, user, actionEnum); + if (validateProductResponse.isRight()) { + return Either.right(validateProductResponse.right().value()); + } + + log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + Either lockResult = lockComponentByName(product.getSystemName(), product, "Create Product"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult); + + try { + Either createProductEither = toscaOperationFacade.createToscaComponent(product); + + if (createProductEither.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + return Either.right(responseFormat); + } + + log.debug("Product created successfully"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum); + + Product createdProduct = createProductEither.left().value(); + + return Either.left(createdProduct); + + } finally { + graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product); + } + + } + + private void checkUnupdatableProductFields(Product product) { + checkComponentFieldsForOverrideAttempt(product); + if (product.getNormalizedName() != null) { + log.info("NormalizedName cannot be defined by user. This field will be overridden by the application"); + } + } + + private Either validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) { + + Either validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum); + if (validateProductFields.isRight()) { + return Either.right(validateProductFields.right().value()); + } + + if (product.getIsActive() == null) { + log.debug("no isActive value was provided, setting to default: false"); + product.setIsActive(false); + } + + product.setCreatorUserId(user.getUserId()); + + // enrich object + log.debug("enrich product with version and state"); + product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + product.setVersion(INITIAL_VERSION); + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + product.setInvariantUUID(invariantUUID); + + return Either.left(product); + } + + private Either validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) { + + // To be removed in 1607 + // See below + String oldName = product.getName(); + + Either componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum); + if (componentNameValidation.isRight()) { + return componentNameValidation; + } + + Either componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum); + if (componentNameUniquenessValidation.isRight()) { + return componentNameUniquenessValidation; + } + + // To be removed in 1607 and replaced with generic + // validateTagsListAndRemoveDuplicates() + // See comments on the validateTagsListAndRemoveDuplicates(user, + // product, oldName, actionEnum) function + Either tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum); + if (tagsValidation.isRight()) { + return tagsValidation; + } + + Either validateIconResponse = validateIcon(user, product, actionEnum); + if (validateIconResponse.isRight()) { + return validateIconResponse; + } + + Either projectCodeValidation = validateProjectCode(user, product, actionEnum); + if (projectCodeValidation.isRight()) { + return projectCodeValidation; + } + Either categoryValidation = validateGrouping(user, product, actionEnum); + if (categoryValidation.isRight()) { + return categoryValidation; + } + + Either contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum); + if (contactsListValidation.isRight()) { + return contactsListValidation; + } + + Either productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum); + if (productFullNameValidation.isRight()) { + return productFullNameValidation; + } + + Either descValidation = validateDescriptionAndCleanup(user, product, actionEnum); + if (descValidation.isRight()) { + return descValidation; + } + + return Either.left(true); + } + + public Either, ResponseFormat> validateProductNameExists(String productName, String userId) { + + Either resp = validateUserExists(userId, "validate Product Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT); + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + private Either validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) { + List contacts = product.getContacts(); + if (!ValidationUtils.validateListNotEmpty(contacts)) { + log.debug("Contacts list cannot be empty for product {}", product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + boolean isProductCreatorInContacts = false; + String modifierUserId = user.getUserId(); + for (String contact : contacts) { + if (contact.equals(modifierUserId)) { + log.trace("modifier userId found in product contacts"); + isProductCreatorInContacts = true; + // No need to validate for this userId - it's modifier's + continue; + } + if (!ValidationUtils.validateContactId(contact)) { + log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + User contactUser = new User(); + contactUser.setUserId(contact); + Either validateUser = validateUserExists(contact, "Create Product", false); + if (validateUser.isRight()) { + log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + contactUser = validateUser.left().value(); + + Either validateUserRole = validateUserRole(contactUser, contactsRoles); + if (validateUserRole.isRight()) { + log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + } + + if (!isProductCreatorInContacts) { + log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId); + contacts.add(modifierUserId); + } + + // passed - setting all contacts userIds to lowercase + List tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList()); + ValidationUtils.removeDuplicateFromList(tempContacts); + product.setContacts(tempContacts); + + return Either.left(true); + } + + private Either validateGrouping(User user, Product product, AuditingActionEnum actionEnum) { + List categories = product.getCategories(); + if (categories == null || categories.isEmpty()) { + log.debug("Grouping list is empty for product: {}", product.getName()); + return Either.left(true); + } + Map>> nonDuplicatedCategories = new HashMap>>(); + // remove duplicated entries + for (CategoryDefinition cat : categories) { + String catName = cat.getName(); + if (ValidationUtils.validateStringNotEmpty(catName) == false) { + // error missing cat name + log.debug("Missing category name for product: {}", product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + Map> catEntry = nonDuplicatedCategories.get(catName); + if (catEntry == null) { + catEntry = new HashMap>(); + nonDuplicatedCategories.put(catName, catEntry); + } + List subcategories = cat.getSubcategories(); + if (subcategories == null || subcategories.isEmpty()) { + // error missing subcat for cat + log.debug("Missing sub-categories for category {} in product {}", catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + for (SubCategoryDefinition subcat : subcategories) { + String subCatName = subcat.getName(); + if (ValidationUtils.validateStringNotEmpty(subCatName) == false) { + // error missing sub cat name for cat + log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + Set subcatEntry = catEntry.get(subCatName); + if (subcatEntry == null) { + subcatEntry = new HashSet(); + catEntry.put(subCatName, subcatEntry); + } + List groupings = subcat.getGroupings(); + for (GroupingDefinition group : groupings) { + String groupName = group.getName(); + if (ValidationUtils.validateStringNotEmpty(groupName) == false) { + // error missing grouping for sub cat name and cat + log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + if (!subcatEntry.contains(groupName)) { + subcatEntry.add(groupName); + } else { + log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName); + } + } + } + } // for end of checking duplicated + // validate existence + Either, ActionStatus> allProductCategories = elementDao.getAllProductCategories(); + + if (allProductCategories.isRight()) { + log.debug("No product categories {}", allProductCategories.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + boolean catExist; + // convert non-duplicated to data modeling format and update in the + // input object + List newCatList = new ArrayList(); + + // over all categories from request + for (Map.Entry>> entry : nonDuplicatedCategories.entrySet()) { + catExist = false; + CategoryDefinition categoryDefinition = null; + // over all categories from Titan + List categoriesList = allProductCategories.left().value(); + if (categoriesList != null) { + for (CategoryDefinition catInDb : categoriesList) { + if (entry.getKey().equals(catInDb.getName())) { + catExist = true; + boolean subcatExist; + // copy data + categoryDefinition = new CategoryDefinition(catInDb); + SubCategoryDefinition subCategory = null; + + Map> subcats = entry.getValue(); + for (Map.Entry> subcat : subcats.entrySet()) { + subcatExist = false; + List subcategoriesList = catInDb.getSubcategories(); + if (subcategoriesList != null) { + for (SubCategoryDefinition subcatInDb : subcategoriesList) { + if (subcatInDb.getName().equals(subcat.getKey())) { + // copy data + subCategory = new SubCategoryDefinition(subcatInDb); + subcatExist = true; + Set grouping = subcat.getValue(); + boolean groupExist; + GroupingDefinition groupingDefinition = null; + for (String group : grouping) { + groupExist = false; + List groupings = subcatInDb.getGroupings(); + if (groupings != null) { + for (GroupingDefinition groupInDb : groupings) { + if (groupInDb.getName().equals(group)) { + groupExist = true; + groupingDefinition = new GroupingDefinition(groupInDb); + } + } + } + if (!groupExist) { + // error grouping isn't defined + // in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + subCategory.addGrouping(groupingDefinition); + } + } + } + } + if (!subcatExist) { + // error sub category isn't defined in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + categoryDefinition.addSubCategory(subCategory); + } + } + } + } + if (!catExist) { + // error category isn't defined in Titan + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey()); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + newCatList.add(categoryDefinition); + } + product.setCategories(newCatList); + return Either.left(true); + } + + public Either getProduct(String productId, User user) { + String ecompErrorContext = "Get product"; + Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either storageStatus = toscaOperationFacade.getToscaElement(productId); + + if (storageStatus.isRight()) { + log.debug("failed to get resource by id {}", productId); + if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + // TODO check error + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue())); + } else { + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + } + return Either.left(storageStatus.left().value()); + } + + public Either deleteProduct(String productId, User user) { + String ecompErrorContext = "Delete product"; + Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either storageStatus = toscaOperationFacade.deleteToscaComponent(productId); + + if (storageStatus.isRight()) { + log.debug("failed to delete resource by id {}", productId); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + return Either.left(storageStatus.left().value()); + } + + private Either validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { + String fullName = product.getFullName(); + if (!ValidationUtils.validateStringNotEmpty(fullName)) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(errorResponse, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(errorResponse); + } + + fullName = ValidationUtils.removeNoneUtf8Chars(fullName); + fullName = ValidationUtils.removeHtmlTags(fullName); + fullName = ValidationUtils.normaliseWhitespace(fullName); + fullName = ValidationUtils.stripOctets(fullName); + + if (!ValidationUtils.validateProductFullNameLength(fullName)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + if (!ValidationUtils.validateIsEnglish(fullName)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + product.setFullName(fullName); + return Either.left(true); + } + + private Either validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) { + String name = product.getName(); + if (!ValidationUtils.validateStringNotEmpty(name)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + // Product name is required to have same validation and normalization as + // category + if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name); + + if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + + product.setName(normalizedName4Display); + String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display); + product.setNormalizedName(normalizedName4Uniqueness); + + return Either.left(true); + } + + // This is a workaround for a current tag--->product name behaviour, which + // will be changed in 1607. + // It was agreed with Ella on 23/2/16 that the tag validation of product + // will be made against the old product name (before normalization), + // and in 1607 US will be defined where UI will no longer pass tag of + // component name, and BE will add it by itself after all needed + // normalizations. + private Either validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) { + List tagsList = product.getTags(); + + Either validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT); + if (validateTags.isRight()) { + ResponseFormat responseFormat = validateTags.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT); + return Either.right(responseFormat); + } + ValidationUtils.removeDuplicateFromList(tagsList); + return Either.left(true); + } + + @Override + public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) { + + } + + public Either updateProductMetadata(String productId, Product updatedProduct, User user) { + ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT; + Either eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + if (updatedProduct == null) { + log.debug("Invalid product json. Check product servlet log for updateProduct entry params"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + + Either storageStatus = toscaOperationFacade.getToscaElement(productId); + if (storageStatus.isRight()) { + if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase())); + } + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), "")); + } + + Product currentProduct = storageStatus.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) { + log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct); + if (validationRsponse.isRight()) { + log.info("product update metadata: validations field."); + return validationRsponse; + } + + Product productToUpdate = validationRsponse.left().value(); + // lock resource + Either lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate); + if (updateResponse.isRight()) { + toscaOperationFacade.rollback(); + log.debug("failed to update product {}", productToUpdate.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + toscaOperationFacade.commit(); + return Either.left(updateResponse.left().value()); + } finally { + graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product); + } + } + + private Either validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion()); + Either response = validateAndUpdateProductName(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateFullName(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateCategory(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateContactList(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateTags(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + if (updatedProduct.getIsActive() != null) { + currentProduct.setIsActive(updatedProduct.getIsActive()); + } + + response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String currentInvariantUuid = currentProduct.getInvariantUUID(); + String updatedInvariantUuid = updatedProduct.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Product invariant UUID is automatically set and cannot be updated"); + updatedProduct.setInvariantUUID(currentInvariantUuid); + } + return Either.left(currentProduct); + + } + + private Either validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) { + String updatedProductName = updatedProduct.getName(); + String tags = ""; + String currentProductName = currentProduct.getName(); + if (updatedProductName != null) { + Either validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null); + if (validatProductNameResponse.isRight()) { + ResponseFormat errorRespons = validatProductNameResponse.right().value(); + return Either.right(errorRespons); + } + updatedProductName = updatedProduct.getName(); + if (!currentProductName.equals(updatedProductName)) { + Either productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null); + if (productNameUniquenessValidation.isRight()) { + return productNameUniquenessValidation; + } + currentProduct.setName(updatedProductName); + tags = updatedProductName; + updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName); + currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName)); + List updatedTags = updatedProduct.getTags(); + // As discussed with Ella currently (1604) we are not removing + // the old name from tags. + if (updatedTags == null) { + updatedTags = currentProduct.getTags(); + } + updatedTags.add(tags); + } + } + return Either.left(true); + } + + private Either validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) { + String updatedProductName = updatedProduct.getFullName(); + String currentProductName = currentProduct.getFullName(); + if (updatedProductName != null && !currentProductName.equals(updatedProductName)) { + Either validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null); + if (validatProductNameResponse.isRight()) { + ResponseFormat errorRespons = validatProductNameResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setFullName(updatedProduct.getFullName()); + } + return Either.left(true); + } + + private Either validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) { + List categoryUpdated = updatedProduct.getCategories(); + + Either validatCategoryResponse = validateGrouping(user, updatedProduct, null); + if (validatCategoryResponse.isRight()) { + ResponseFormat errorResponse = validatCategoryResponse.right().value(); + return Either.right(errorResponse); + } + + categoryUpdated = updatedProduct.getCategories(); + if (categoryUpdated != null) { + currentProduct.setCategories(categoryUpdated); + } + return Either.left(true); + } + + private Either validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) { + List updatedContacts = updatedProduct.getContacts(); + List currentContacts = currentProduct.getContacts(); + if (updatedContacts != null) { + if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) { + Either validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setContacts(updatedProduct.getContacts()); + } + } + return Either.left(true); + } + + private Either validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) { + List tagsUpdated = updatedProduct.getTags(); + List tagsCurrent = currentProduct.getTags(); + if (tagsUpdated != null) { + if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { + Either validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentProduct.setTags(updatedProduct.getTags()); + } + } + return Either.left(true); + } + + @Override + public Either, ResponseFormat> deleteMarkedComponents() { + // markAsDeleted isnt implemented yet + return Either.left(new ArrayList<>()); + } + + @Override + protected boolean validateTagPattern(String tag) { + return ValidationUtils.validateCategoryDisplayNameFormat(tag); + } + + public Either getProductByNameAndVersion(String productName, String productVersion, String userId) { + Either resp = validateUserExists(userId, "get Service By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion); + if (storageStatus.isRight()) { + log.debug("failed to get service by name {} and version {}", productName, productVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName)); + } + Product product = storageStatus.left().value(); + return Either.left(product); + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + @Override + public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + @Override + public Either getUiComponentDataTransferByComponentId(String componentId, + List dataParamsToReturn) { + // TODO Auto-generated method stub + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java deleted file mode 100644 index 73f72216d2..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.springframework.stereotype.Component; - -@Component("productComponentInstanceBusinessLogic") -public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - // TODO Pavel this might be also a resource? - return NodeTypeEnum.Service; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - // TODO Auto-generated method stub - return ComponentTypeEnum.SERVICE_INSTANCE; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index ff26ced5c9..9cc4b9cd3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -20,16 +20,8 @@ package org.openecomp.sdc.be.components.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Supplier; - -import javax.servlet.ServletContext; - +import com.google.gson.JsonElement; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -41,20 +33,17 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.resources.data.EntryData; -import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -62,513 +51,479 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Supplier; @Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { - private static final String CREATE_PROPERTY = "CreateProperty"; - - private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName()); - - private static final String EMPTY_VALUE = null; - - private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - protected static IElementOperation getElementDao(Class class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - public Either, ResponseFormat> getAllDataTypes() { - Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); - return eitherAllDataTypes; - } - - /** - * Create new property on resource in graph - * - * @param resourceId - * @param propertyName - * @param newPropertyDefinition - * @param userId - * @return Either - */ - public Either, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { - - Either, ResponseFormat> result = null; - - Either resp = validateUserExists(userId, "create Property", false); - if (resp.isRight()) { - result = Either.right(resp.right().value()); - return result; - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return result; - } - Resource resource = status.left().value(); - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return result; - } - - // verify property not exist in resource - List resourceProperties = resource.getProperties(); - - if (resourceProperties != null) { - if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); - return result; - } - } - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - - Map dataTypes = allDataTypes.left().value(); - - // validate property default values - Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - // convert property - ToscaPropertyType type = getType(newPropertyDefinition.getType()); - if (type != null) { - PropertyValueConverter converter = type.getConverter(); - // get inner type - String innerType = null; - if (newPropertyDefinition != null) { - SchemaDefinition schema = newPropertyDefinition.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (prop != null) { - innerType = prop.getType(); - } - } - String convertedValue = null; - if (newPropertyDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); - newPropertyDefinition.setDefaultValue(convertedValue); - } - } - } - - // add the new property to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus - // from componentsUtils - Either either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - PropertyDefinition createdPropertyDefinition = either.left().value(); - EntryData property = new EntryData(propertyName, createdPropertyDefinition); - result = Either.left(property); - return result; - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - /** - * Get property of resource - * - * @param resourceId - * @param propertyId - * @param userId - * @return - */ - public Either, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { - - Either resp = validateUserExists(userId, "create Component Instance", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - // verify property exist in resource - List properties = resource.getProperties(); - if (properties == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); - } - for (PropertyDefinition property : properties) { - if (property.getUniqueId().equals(propertyId) ) { - Map propMap = new HashMap<>(); - propMap.put(property.getName(), property); - return Either.left(propMap.entrySet().iterator().next()); - } - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); - } - - private boolean isPropertyBelongsToResource(PropertyDataDefinition property, String resourceId) { - return property.getOwnerId() == null || property.getOwnerId().equals(resourceId); - } - - /** - * delete property of resource from graph - * - * @param resourceId - * @param propertyId - * @param userId - * @return - */ - public Either, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { - - Either, ResponseFormat> result = null; - - Either resp = validateUserExists(userId, "delete Property", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - - // Get the resource from DB - Either getResourceRes = toscaOperationFacade.getToscaElement(resourceId); - if (getResourceRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - return result; - } - Resource resource = getResourceRes.left().value(); - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - return result; - } - - // verify property exist in resource - Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); - if (statusGetProperty.isRight()) { - result = Either.right(statusGetProperty.right().value()); - return result; - } - - StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); - if (status != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); - return result; - } - // propertyOperation.getTitanGenericDao().commit(); - result = Either.left(statusGetProperty.left().value()); - return result; - - } finally { - commitOrRollback(result); - // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - } - - /** - * update property - * - * @param resourceId - * @param propertyId - * @param newPropertyDefinition - * @param userId - * @return - */ - public Either, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) { - - Either, ResponseFormat> result = null; - - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - Resource resource = status.left().value(); - - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - - try { - Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); - if (statusGetProperty.isRight()) { - result = Either.right(statusGetProperty.right().value()); - return result; - } - String propertyName = statusGetProperty.left().value().getKey(); - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - Map dataTypes = allDataTypes.left().value(); - - Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - - Either either = handleProperty(propertyId, newPropertyDefinition, dataTypes); - if (either.isRight()) { - log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - - either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - EntryData property = new EntryData(propertyName, either.left().value()); - result = Either.left(property); - return result; - - } finally { - commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - private boolean isPropertyExist(List properties, String resourceUid, String propertyName, String propertyType) { - boolean result = false; - if (!CollectionUtils.isEmpty(properties)) { - for (PropertyDefinition propertyDefinition : properties) { - - if ( propertyDefinition.getName().equals(propertyName) && - (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { - result = true; - break; - } - } - } - return result; - } - - private PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) { - log.debug("The object returned after create property is {}", propertyDataResult); - PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition()); - propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints())); - propertyDefResult.setName(propertyName); - propertyDefResult.setParentUniqueId(resourceId); - return propertyDefResult; - } - - private List convertConstraints(List constraints) { - - if (constraints == null || constraints.size() == 0) { - return null; - } - - List list = new ArrayList(); - Type constraintType = new TypeToken() { - }.getType(); - - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - for (String constraintJson : constraints) { - PropertyConstraint propertyConstraint = gson.fromJson(constraintJson, constraintType); - list.add(propertyConstraint); - } - - return list; - } - - private Either handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map dataTypes) { - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - return Either.right(validateAndUpdateProperty); - } - - return Either.left(newPropertyDefinition); - } - - private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map dataTypes) { - - log.trace("Going to validate property type and value. {}", propertyDefinition); - - String propertyType = propertyDefinition.getType(); - String value = propertyDefinition.getDefaultValue(); - - ToscaPropertyType type = getType(propertyType); - - if (type == null) { - - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (dataTypeDefinition == null) { - log.debug("The type {} of property cannot be found.", propertyType); - return StorageOperationStatus.INVALID_TYPE; - } - - StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); - - return status; - - } - String innerType = null; - - Either checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); - if (checkInnerType.isRight()) { - return StorageOperationStatus.INVALID_TYPE; - } - innerType = checkInnerType.left().value(); - - log.trace("After validating property type {}", propertyType); - - boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", value, type); - return StorageOperationStatus.INVALID_VALUE; - } - - PropertyValueConverter converter = type.getConverter(); - - if (isEmptyValue(value)) { - log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); - propertyDefinition.setDefaultValue(EMPTY_VALUE); - } else if (false == isEmptyValue(value)) { - String convertedValue = converter.convert(value, innerType, dataTypes); - propertyDefinition.setDefaultValue(convertedValue); - } - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, - - String value, DataTypeDefinition dataTypeDefinition, Map dataTypes) { - - ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); - - if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); - return StorageOperationStatus.INVALID_VALUE; - } - - JsonElement jsonElement = validateResult.left; - - log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); - - updateValue(propertyDefinition, jsonElement); - - return StorageOperationStatus.OK; - } - - protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { - - propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); - - } - - protected String getValueFromJsonElement(JsonElement jsonElement) { - String value = null; - - if (jsonElement == null || jsonElement.isJsonNull()) { - value = EMPTY_VALUE; - } else { - if (jsonElement.toString().isEmpty()) { - value = ""; - } else { - value = jsonElement.toString(); - } - } - - return value; - } - - protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { - String innerType = null; - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - - SchemaDefinition def = schemeGen.get();// propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - return Either.left(innerType); - } - protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { - if (isEmptyValue(value)) { - return true; - } - - PropertyTypeValidator validator = type.getValidator(); - - boolean isValid = validator.isValid(value, innerType, dataTypes); - if (true == isValid) { - return true; - } else { - return false; - } - - } - - public boolean isEmptyValue(String value) { - if (value == null) { - return true; - } - return false; - } + private static final String CREATE_PROPERTY = "CreateProperty"; + + private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class); + + private static final String EMPTY_VALUE = null; + + private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + protected static IElementOperation getElementDao(Class class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + public Either, ResponseFormat> getAllDataTypes() { + Either, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); + return eitherAllDataTypes; + } + + /** + * Create new property on resource in graph + * + * @param resourceId + * @param propertyName + * @param newPropertyDefinition + * @param userId + * @return Either + */ + public Either, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { + + Either, ResponseFormat> result = null; + + Either resp = validateUserExists(userId, "create Property", false); + if (resp.isRight()) { + result = Either.right(resp.right().value()); + return result; + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + // Get the resource from DB + Either status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + return result; + } + Resource resource = status.left().value(); + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return result; + } + + // verify property not exist in resource + List resourceProperties = resource.getProperties(); + + if (resourceProperties != null) { + if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); + return result; + } + } + + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + + Map dataTypes = allDataTypes.left().value(); + + // validate property default values + Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + result = Either.right(defaultValuesValidation.right().value()); + return result; + } + // convert property + ToscaPropertyType type = getType(newPropertyDefinition.getType()); + if (type != null) { + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + if (newPropertyDefinition != null) { + SchemaDefinition schema = newPropertyDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newPropertyDefinition.getDefaultValue() != null) { + convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); + newPropertyDefinition.setDefaultValue(convertedValue); + } + } + } + + // add the new property to resource on graph + // need to get StorageOpaerationStatus and convert to ActionStatus + // from componentsUtils + Either either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + PropertyDefinition createdPropertyDefinition = either.left().value(); + EntryData property = new EntryData(propertyName, createdPropertyDefinition); + result = Either.left(property); + return result; + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + /** + * Get property of resource + * + * @param resourceId + * @param propertyId + * @param userId + * @return + */ + public Either, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { + + Either resp = validateUserExists(userId, "create Component Instance", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + // Get the resource from DB + Either status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + // verify property exist in resource + List properties = resource.getProperties(); + if (properties == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); + } + for (PropertyDefinition property : properties) { + if (property.getUniqueId().equals(propertyId) ) { + Map propMap = new HashMap<>(); + propMap.put(property.getName(), property); + return Either.left(propMap.entrySet().iterator().next()); + } + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); + } + + /** + * delete property of resource from graph + * + * @param resourceId + * @param propertyId + * @param userId + * @return + */ + public Either, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { + + Either, ResponseFormat> result = null; + + Either resp = validateUserExists(userId, "delete Property", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + + // Get the resource from DB + Either getResourceRes = toscaOperationFacade.getToscaElement(resourceId); + if (getResourceRes.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + return result; + } + Resource resource = getResourceRes.left().value(); + + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + return result; + } + + // verify property exist in resource + Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + if (statusGetProperty.isRight()) { + result = Either.right(statusGetProperty.right().value()); + return result; + } + + StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); + if (status != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); + return result; + } + result = Either.left(statusGetProperty.left().value()); + return result; + + } finally { + commitOrRollback(result); + // unlock component + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + } + + /** + * update property + * + * @param resourceId + * @param propertyId + * @param newPropertyDefinition + * @param userId + * @return + */ + public Either, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) { + + Either, ResponseFormat> result = null; + + Either status = toscaOperationFacade.getToscaElement(resourceId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Resource resource = status.left().value(); + + if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + return result; + } + + try { + Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + if (statusGetProperty.isRight()) { + result = Either.right(statusGetProperty.right().value()); + return result; + } + String propertyName = statusGetProperty.left().value().getKey(); + + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + Map dataTypes = allDataTypes.left().value(); + + Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + result = Either.right(defaultValuesValidation.right().value()); + return result; + } + + Either either = handleProperty(propertyId, newPropertyDefinition, dataTypes); + if (either.isRight()) { + log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + + either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); + if (either.isRight()) { + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + return result; + } + + EntryData property = new EntryData(propertyName, either.left().value()); + result = Either.left(property); + return result; + + } finally { + commitOrRollback(result); + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + private boolean isPropertyExist(List properties, String resourceUid, String propertyName, String propertyType) { + boolean result = false; + if (!CollectionUtils.isEmpty(properties)) { + for (PropertyDefinition propertyDefinition : properties) { + + if ( propertyDefinition.getName().equals(propertyName) && + (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { + result = true; + break; + } + } + } + return result; + } + + private Either handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map dataTypes) { + + StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + return Either.right(validateAndUpdateProperty); + } + + return Either.left(newPropertyDefinition); + } + + private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map dataTypes) { + + log.trace("Going to validate property type and value. {}", propertyDefinition); + + String propertyType = propertyDefinition.getType(); + String value = propertyDefinition.getDefaultValue(); + + ToscaPropertyType type = getType(propertyType); + + if (type == null) { + + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (dataTypeDefinition == null) { + log.debug("The type {} of property cannot be found.", propertyType); + return StorageOperationStatus.INVALID_TYPE; + } + + StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); + + return status; + + } + String innerType = null; + + Either checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); + if (checkInnerType.isRight()) { + return StorageOperationStatus.INVALID_TYPE; + } + innerType = checkInnerType.left().value(); + + log.trace("After validating property type {}", propertyType); + + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (false == isValidProperty) { + log.info("The value {} of property from type {} is invalid", value, type); + return StorageOperationStatus.INVALID_VALUE; + } + + PropertyValueConverter converter = type.getConverter(); + + if (isEmptyValue(value)) { + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); + propertyDefinition.setDefaultValue(EMPTY_VALUE); + } else if (false == isEmptyValue(value)) { + String convertedValue = converter.convert(value, innerType, dataTypes); + propertyDefinition.setDefaultValue(convertedValue); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, + + String value, DataTypeDefinition dataTypeDefinition, Map dataTypes) { + + ImmutablePair validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + + if (validateResult.right.booleanValue() == false) { + log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); + return StorageOperationStatus.INVALID_VALUE; + } + + JsonElement jsonElement = validateResult.left; + + log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , jsonElement); + + updateValue(propertyDefinition, jsonElement); + + return StorageOperationStatus.OK; + } + + protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { + + propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); + + } + + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; + + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + if (jsonElement.toString().isEmpty()) { + value = ""; + } else { + value = jsonElement.toString(); + } + } + + return value; + } + + protected Either getInnerType(ToscaPropertyType type, Supplier schemeGen) { + String innerType = null; + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + + SchemaDefinition def = schemeGen.get(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + return Either.left(innerType); + } + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map dataTypes) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + boolean isValid = validator.isValid(value, innerType, dataTypes); + if (true == isValid) { + return true; + } else { + return false; + } + + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java index bd7e810066..6454379af8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java @@ -27,13 +27,13 @@ import org.springframework.stereotype.Component; @Component("requirementsBusinessLogic") public class RequirementsBusinessLogic { - private static Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class); - @javax.annotation.Resource - private ComponentsUtils componentsUtils; + @javax.annotation.Resource + private ComponentsUtils componentsUtils; - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index 4924bd25a7..f6cb50c5c2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -20,33 +20,15 @@ package org.openecomp.sdc.be.components.impl; -import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH; -import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; +import com.google.gson.Gson; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; @@ -59,7 +41,6 @@ import org.openecomp.sdc.be.components.merge.resource.MergeResourceBLFactory; import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; -import org.openecomp.sdc.be.config.Configuration.VfModuleProperty; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -74,8 +55,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.info.ArtifactTemplateInfo; -import org.openecomp.sdc.be.info.MergedArtifactInfo; +import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; @@ -90,7 +70,6 @@ import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; @@ -113,7 +92,6 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; -import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; @@ -127,7 +105,7 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; @@ -138,7 +116,6 @@ import org.openecomp.sdc.be.utils.CommonBeUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; @@ -153,7288 +130,6634 @@ import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.parser.ParserException; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import javax.servlet.ServletContext; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN; @org.springframework.stereotype.Component("resourceBusinessLogic") public class ResourceBusinessLogic extends ComponentBusinessLogic { - private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; - public static final String INITIAL_VERSION = "0.1"; + private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes"; + public static final String INITIAL_VERSION = "0.1"; + + private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); + private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); + private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); + private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); + private Pattern GET_ATTRIBUTE_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_attribute" + "="); - private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "="); - private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "="); - private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "="); - private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "="); + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class); - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName()); + private static Pattern pattern = Pattern.compile("\\..(.*?)\\.."); - private static Pattern pattern = Pattern.compile("\\..(.*?)\\.."); + /** + * Default constructor + */ + public ResourceBusinessLogic() { + log.debug("ResourceBusinessLogic started"); + } - /** - * Default constructor - */ - public ResourceBusinessLogic() { - log.debug("ResourceBusinessLogic started"); - } + @Autowired + private ICapabilityTypeOperation capabilityTypeOperation = null; - @Autowired - private ICapabilityTypeOperation capabilityTypeOperation = null; + @Autowired + private IInterfaceLifecycleOperation interfaceTypeOperation = null; - @Autowired - private IInterfaceLifecycleOperation interfaceTypeOperation = null; + @Autowired + private LifecycleBusinessLogic lifecycleBusinessLogic; - @Autowired - private LifecycleBusinessLogic lifecycleBusinessLogic; + @Autowired + private IPropertyOperation propertyOperation; - @Autowired - private IPropertyOperation propertyOperation; + @Autowired + private CsarOperation csarOperation; - @Autowired - private CsarOperation csarOperation; + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @Autowired - private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic; + @Autowired + private ResourceImportManager resourceImportManager; - @Autowired - private ResourceImportManager resourceImportManager; - @Autowired - private GroupBusinessLogic groupBusinessLogic; - - @Autowired - private InputsBusinessLogic inputsBusinessLogic; - - @Autowired - private CompositionBusinessLogic compositionBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private MergeResourceBLFactory mergeResourceBLFactory; + @Autowired + private InputsBusinessLogic inputsBusinessLogic; - private Gson gson = new Gson(); - - public CsarOperation getCsarOperation() { - return csarOperation; - } - - public void setCsarOperation(CsarOperation csarOperation) { - this.csarOperation = csarOperation; - } - - public LifecycleBusinessLogic getLifecycleBusinessLogic() { - return lifecycleBusinessLogic; - } - - public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { - this.lifecycleBusinessLogic = lifecycleBusinessLogic; - } - - public IElementOperation getElementDao() { - return elementDao; - } - - public void setElementDao(IElementOperation elementDao) { - this.elementDao = elementDao; - } - - public IUserBusinessLogic getUserAdmin() { - return this.userAdmin; - } - - public void setUserAdmin(UserBusinessLogic userAdmin) { - this.userAdmin = userAdmin; - } - - public ComponentsUtils getComponentsUtils() { - return this.componentsUtils; - } - - public void setComponentsUtils(ComponentsUtils componentsUtils) { - this.componentsUtils = componentsUtils; - } - - public ArtifactsBusinessLogic getArtifactsManager() { - return artifactsBusinessLogic; - } - - public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { - this.artifactsBusinessLogic = artifactsManager; - } - - public void setPropertyOperation(IPropertyOperation propertyOperation) { - this.propertyOperation = propertyOperation; - } - - public ApplicationDataTypeCache getApplicationDataTypeCache() { - return applicationDataTypeCache; - } - - public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { - this.applicationDataTypeCache = applicationDataTypeCache; - } - - /** - * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param - * - * @param getAbstract - * @param userId TODO - * @return - */ - public Either, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) { - Either resp = validateUserExists(userId, "get All Certified Resources", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Boolean isHighest = null; - switch (highestFilter) { - case ALL: - break; - case HIGHEST_ONLY: - isHighest = true; - break; - case NON_HIGHEST_ONLY: - isHighest = false; - break; - default: - break; - } - Either, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest); - - if (getResponse.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value()))); - } - - return Either.left(getResponse.left().value()); - } - - public Either, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) { - - Either resp = validateUserExists(userId, "validate Resource Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - public Either createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map csarUIPayload, String payloadName) { - Either createResourceResponse = validateResourceBeforeCreate(resource, user, false); - if (createResourceResponse.isRight()) { - return createResourceResponse; - } - - // Creating resource either by DAO or from CSAR - String csarUUID = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - } else { - csarUUID = payloadName; - } - if (csarUUID != null && !csarUUID.isEmpty()) { - // check if VF with the same Csar UUID or with he same name already - // exists - Either validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID); - if (validateCsarUuidUniquenessRes.isRight()) { - log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value()))); - } - - Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value(); - if (existingResourceRes.intValue() > 0) { - log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID); - componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null); - return Either.right(errorResponse); - } - - log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); - createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID); - return createResourceResponse; - } - - return createResourceByDao(resource, user, auditingAction, false, false, null); - } - - public Either validateAndUpdateResourceFromCsar(Resource resource, User user, Map csarUIPayload, String payloadName, String resourceUniqueId) { - Either updateResourceResponse = null; - Either validateResourceResponse = null; - Wrapper responseWrapper = new Wrapper(); - String csarUUID = null; - String csarVersion = null; - if (payloadName == null) { - csarUUID = resource.getCsarUUID(); - csarVersion = resource.getCsarVersion(); - } else { - csarUUID = payloadName; - } - if (csarUUID != null && !csarUUID.isEmpty()) { - Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId); - if (responseWrapper.isEmpty()) { - validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user); - } - if (responseWrapper.isEmpty()) { - validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user); - } - if (responseWrapper.isEmpty()) { - if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { - overrideImmutableMetadata(oldResource, resource); - } - validateResourceResponse = validateResourceBeforeCreate(resource, user, false); - if (validateResourceResponse.isRight()) { - responseWrapper.setInnerElement(validateResourceResponse.right().value()); - } - } - if (responseWrapper.isEmpty()) { - String oldCsarVersion = oldResource.getCsarVersion(); - log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId); - // (on boarding flow): If the update includes same csarUUID and - // same csarVersion as already in the VF - no need to import the - // csar (do only metadata changes if there are). - if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { - updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false); - } else { - updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID); - } - } - } else { - log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - responseWrapper.setInnerElement(errorResponse); - } - if (responseWrapper.isEmpty()) { - return updateResourceResponse; - } - return Either.right(responseWrapper.getInnerElement()); - } - - private void validateCsarIsNotAlreadyUsed(Wrapper responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) { - // (on boarding flow): If the update includes a csarUUID: verify this - // csarUUID is not in use by another VF, If it is - use same error as - // above: - // "Error: The VSP with UUID %1 was already imported for VF %2. Please - // select another or update the existing VF." %1 - csarUUID, %2 - VF - // name - Either resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); - if (resourceLinkedToCsarRes.isRight()) { - if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { - log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName()); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value()))); - } - } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName()); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null); - responseWrapper.setInnerElement(errorResponse); - } - } - - private void validateCsarUuidMatching(Wrapper responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) { - // (on boarding flow): If the update includes csarUUID which is - // different from the csarUUID of the VF - fail with - // error: "Error: Resource %1 cannot be updated using since it is linked - // to a different VSP" %1 - VF name - String oldCsarUUID = oldResource.getCsarUUID(); - if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { - log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); - componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null); - responseWrapper.setInnerElement(errorResponse); - } - } - - private Resource getResourceByUniqueId(Wrapper responseWrapper, String resourceUniqueId) { - Either oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId); - if (oldResourceRes.isRight()) { - log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value()); - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value()))); - return null; - } - return oldResourceRes.left().value(); - } - - private void overrideImmutableMetadata(Resource oldRresource, Resource resource) { - resource.setName(oldRresource.getName()); - resource.setIcon(oldRresource.getIcon()); - resource.setTags(oldRresource.getTags()); - resource.setVendorName(oldRresource.getVendorName()); - resource.setCategories(oldRresource.getCategories()); - resource.setDerivedFrom(oldRresource.getDerivedFrom()); - } - - private Either updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either, StorageOperationStatus> csarUIPayload, - String csarUUID) { - - // check state - if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) { - if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) { - log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - String lockedResourceId = oldRresource.getUniqueId(); - List createdArtifacts = new ArrayList<>(); - - Either, StorageOperationStatus> csar = null; - if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { - csar = csarUIPayload; - } else { - csar = csarOperation.getCsar(csarUUID, user); - } - if (csar.isRight()) { - log.debug("Failed to get csar for casrUUID{} ", csarUUID); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value()))); - } - - Either, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar); - if (toscaYamlCsarStatus.isRight()) { - return Either.right(toscaYamlCsarStatus.right().value()); - } - Either checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils); - if (checksum.isRight()) { - log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value()); - return Either.right(checksum.right().value()); - } - boolean isUpdateYaml = true; - if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) { - log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value()); - if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) - isUpdateYaml = false; - } else { - oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value()); - } - - Either lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - - String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); - String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); - CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, true); - Map nodeTypesInfo = extractNodeTypesInfo(csarInfo); - Either result = null; - - Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, oldRresource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); - result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); - return result; - } - Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value(); - try{ - result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); - - } finally { - if (result == null || result.isRight()) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - return result; - - } - - private Either updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List createdArtifacts, - boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, - Map>> nodeTypesArtifactsToHandle, String nodeName, boolean isNested) { - Either result; - Either, ResponseFormat> parseNodeTypeInfoYamlEither; - boolean inTransaction = true; - boolean shouldLock = false; - - Either, ResponseFormat> prepareForUpdate; - Resource preparedResource; - Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName); - if (uploadComponentInstanceInfoMap.isRight()) { - ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - - Map instances = uploadComponentInstanceInfoMap.left().value().getInstances(); - - if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) { - - prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock, isNested); - if (prepareForUpdate.isRight()) { - log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); - result = Either.right(prepareForUpdate.right().value()); - return result; - } - preparedResource = prepareForUpdate.left().value().left; - - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); - - Either genericResourceEither = handleResourceGenericType(preparedResource); - if (genericResourceEither.isRight()) { - log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value()); - ResponseFormat responseFormat = genericResourceEither.right().value(); - componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - return Either.right(responseFormat); - } - - parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); - if (parseNodeTypeInfoYamlEither.isRight()) { - ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - - Map inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); - Either createInputsOnResource = createInputsOnResource(preparedResource, csarInfo.getModifier(), inputs, inTransaction); - if (createInputsOnResource.isRight()) { - log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value()); - ResponseFormat responseFormat = createInputsOnResource.right().value(); - componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - preparedResource = createInputsOnResource.left().value(); - - Either createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, csarInfo.getCreatedNodes()); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); - ResponseFormat responseFormat = createResourcesInstancesEither.right().value(); - componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - preparedResource = createResourcesInstancesEither.left().value(); - - createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value()); - result = Either.right(createResourcesInstancesEither.right().value()); - return result; - } - - preparedResource = createResourcesInstancesEither.left().value(); - - Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { - - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - // add groups to resource - Map groups; - - if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left().value(); - } else { - groups = uploadComponentInstanceInfoMap.left().value().getGroups(); - } - Either updatedGroupsOnResource = updateGroupsOnResource(preparedResource, csarInfo.getModifier(), groups); - if (updatedGroupsOnResource.isRight()) { - - return updatedGroupsOnResource; - } - preparedResource = updatedGroupsOnResource.left().value(); - - } else { - Either dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, csarInfo.getModifier(), oldRresource, shouldLock, inTransaction); - if (dataModelResponse.isRight()) { - log.debug("failed to update resource metadata {}", dataModelResponse.right().value()); - result = Either.right(dataModelResponse.right().value()); - return result; - } - preparedResource = dataModelResponse.left().value(); - } - - if(preparedResource.getResourceType() == ResourceTypeEnum.CVFC){ - if(nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()){ - Either, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - } else { - Either createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), shouldLock, inTransaction); - log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); - if (createdCsarArtifactsEither.isRight()) { - return createdCsarArtifactsEither; - } - preparedResource = createdCsarArtifactsEither.left().value(); - } - - ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource); - if (mergingPropsAndInputsStatus != ActionStatus.OK) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource); - return Either.right(responseFormat); - } - - Either, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); - result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource); - - return result; - - } - - private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { - Either mergeResourceBLEither = mergeResourceBLFactory.getInstance(oldResource, newResource); - if (mergeResourceBLEither.isRight()) { - return mergeResourceBLEither.right().value(); - } - MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value(); - return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource); - } - - private Either handleResourceGenericType(Resource resource) { - Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); - if (genericResourceEither.isRight()) { - return genericResourceEither; - } - if (resource.shouldGenerateInputs()) { - generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); - } - return genericResourceEither; - } - - private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { - - Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar()); - Map>> nodeTypesArtifactsToHandle = new HashMap<>(); - Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes; - - try { - nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - Map> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo); - Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes; - EnumMap> curNodeTypeArtifactsToHandle = null; - log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID()); - - for (Entry> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) { - String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft(); - String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight(); - String currNamespace = currVfcToscaNameEntry.getKey(); - log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName); - - Either curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName); - Resource curNodeType = null; - if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { - curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName); - } - if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { - log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarInfo.getCsarUUID()); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - break; - } else if (curVfcRes.isLeft()) { - curNodeType = curVfcRes.left().value(); - } - if (!MapUtils.isEmpty(extractedVfcsArtifacts)) { - List currArtifacts = new ArrayList<>(); - if (extractedVfcsArtifacts.containsKey(currNamespace)) { - handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace)); - } - curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); - if (curNodeTypeArtifactsToHandleRes.isRight()) { - nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value()); - break; - } - curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value(); - - } else if (curNodeType != null) { - // delete all artifacts if have not received artifacts from csar - curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - List artifactsToDelete = new ArrayList<>(); - // delete all informational artifacts - artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList())); - // delete all deployment artifacts - artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); - if (!artifactsToDelete.isEmpty()) { - curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - } - if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) { - nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle); - } - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - nodeTypesArtifactsToHandleRes = Either.right(responseFormat); - log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); - } - return nodeTypesArtifactsToHandleRes; - } - - private Either>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List extractedArtifacts) { - - Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = null; - EnumMap> nodeTypeArtifactsToHandle = null; - Wrapper responseWrapper = new Wrapper<>(); - try { - List artifactsToUpload = new ArrayList<>(extractedArtifacts); - List artifactsToUpdate = new ArrayList<>(); - List artifactsToDelete = new ArrayList<>(); - if (curNodeType != null) { - Map existingArtifacts = new HashMap<>(); - if (curNodeType.getDeploymentArtifacts() != null) { - existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); - } - if (curNodeType.getArtifacts() != null) { - existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); - } - for (ArtifactDefinition currNewArtifact : extractedArtifacts) { - ArtifactDefinition foundArtifact; - - if (!existingArtifacts.isEmpty()) { - foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); - if (foundArtifact != null) { - if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - foundArtifact.setPayload(currNewArtifact.getPayloadData()); - foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData())); - foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); - artifactsToUpdate.add(foundArtifact); - } - existingArtifacts.remove(foundArtifact.getArtifactLabel()); - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.getArtifactType()); - responseWrapper.setInnerElement(responseFormat); - break; - } - } - } - } - if (responseWrapper.isEmpty()) { - artifactsToDelete.addAll(existingArtifacts.values()); - } - } - if (responseWrapper.isEmpty()) { - if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { - nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - if (!artifactsToUpload.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); - if (!artifactsToUpdate.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); - if (!artifactsToDelete.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); - } - if (!responseWrapper.isEmpty()) { - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - } - return nodeTypeArtifactsToHandleRes; - } - - /** - * Changes resource life cycle state to checked out - * - * @param resource - * @param user - * @param inTransaction - * @return - */ - private Either checkoutResource(Resource resource, User user, boolean inTransaction) { - Either checkoutResourceRes; - try { - if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName()); - Either checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true); - if (checkoutRes.isRight()) { - log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus()); - checkoutResourceRes = Either.right(checkoutRes.right().value()); - } else { - checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); - } - } else { - checkoutResourceRes = Either.left(resource); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - checkoutResourceRes = Either.right(responseFormat); - log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e); - } - return checkoutResourceRes; - } - - /** - * Handles Artifacts of NodeType - * - * @param nodeTypeResource - * @param nodeTypeArtifactsToHandle - * @param vfcsNewCreatedArtifacts - * @param user - * @param inTransaction - * @return - */ - public Either, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map> nodeTypeArtifactsToHandle, List createdArtifacts, - User user, boolean inTransaction, boolean ignoreLifecycleState) { - Either, ResponseFormat> handleNodeTypeArtifactsRequestRes; - Either, ResponseFormat> handleNodeTypeArtifactsRes = null; - Either changeStateResponse; - try { - changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); - if (changeStateResponse.isRight()) { - return Either.right(changeStateResponse.right().value()); - } - nodeTypeResource = changeStateResponse.left().value(); - - List handledNodeTypeArtifacts = new ArrayList<>(); - log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); - for (Entry> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) { - ArtifactOperationEnum curOperation = curOperationEntry.getKey(); - List curArtifactsToHandle = curOperationEntry.getValue(); - if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { - log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName()); - handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts, - artifactsBusinessLogic.new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction); - if (handleNodeTypeArtifactsRequestRes.isRight()) { - handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); - break; - } - if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { - createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); - } - } - if (handleNodeTypeArtifactsRes == null) { - handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - handleNodeTypeArtifactsRes = Either.right(responseFormat); - log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); - } - return handleNodeTypeArtifactsRes; - } - - private Map> extractVfcToscaNames(Map nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) { - Map> vfcToscaNames = new HashMap<>(); - - Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); - if (!nodes.isEmpty()) { - Iterator> nodesNameEntry = nodes.entrySet().iterator(); - while (nodesNameEntry.hasNext()) { - Entry nodeType = nodesNameEntry.next(); - ImmutablePair toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); - vfcToscaNames.put(nodeType.getKey(), toscaResourceName); - } - } - for(NodeTypeInfo cvfc : nodeTypesInfo.values()){ - vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); - } - return vfcToscaNames; - } - - private Map extractAllNodes(Map nodeTypesInfo, CsarInfo csarInfo) { - Map nodes = new HashMap<>(); - for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){ - extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); - } - extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); - return nodes; - } - - private void extractNodeTypes(Map nodes, Map mappedToscaTemplate) { - Either, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (eitherNodeTypes.isLeft()) { - nodes.putAll(eitherNodeTypes.left().value()); - } - } - - public Either createResourceFromCsar(Resource resource, User user, Either, StorageOperationStatus> csarUIPayload, String csarUUID) { - log.trace("************* created successfully from YAML, resource TOSCA "); - - Either, StorageOperationStatus> csar = null; - if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { - csar = csarUIPayload; - } else { - csar = csarOperation.getCsar(csarUUID, user); - } - - Either, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar); - if (toscaYamlCsarStatus.isRight()) { - return Either.right(toscaYamlCsarStatus.right().value()); - } - Either toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils); - if (toscaYamlChecksum.isRight()) { - log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value()); - return Either.right(toscaYamlChecksum.right().value()); - } - resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value()); - - String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); - String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); - log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); - - CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false); - Map nodeTypesInfo = extractNodeTypesInfo(csarInfo); - Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource); - if (findNodeTypesArtifactsToHandleRes.isRight()) { - log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID()); - return Either.right(findNodeTypesArtifactsToHandleRes.right().value()); - } - Either createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null); - if (createResourceFromYaml.isRight()) { - log.debug("Couldn't create resource from YAML"); - return Either.right(createResourceFromYaml.right().value()); - } - - Resource vfResource = createResourceFromYaml.left().value(); - log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName()); - return Either.left(vfResource); - } - - private Map extractNodeTypesInfo(CsarInfo csarInfo) { - Map nodeTypesInfo = new HashMap<>(); - List> globalSubstitutes = new ArrayList<>(); - for (Map.Entry entry : csarInfo.getCsar().entrySet()) { - extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry); - } - if (CollectionUtils.isNotEmpty(globalSubstitutes)) { - setDerivedFrom(nodeTypesInfo, globalSubstitutes); - } - markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo); - return nodeTypesInfo; - } - - @SuppressWarnings("unchecked") - private void setDerivedFrom(Map nodeTypesInfo, List> globalSubstitutes) { - for (Map.Entry entry : globalSubstitutes) { - String yamlFileContents = new String(entry.getValue()); - Map mappedToscaTemplate = (Map) new Yaml().load(yamlFileContents); - Either nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); - if (nodeTypesEither.isLeft()) { - Map nodeTypes = (Map) nodeTypesEither.left().value(); - for (Entry nodeType : nodeTypes.entrySet()) { - Map nodeTypeMap = (Map) nodeType.getValue(); - if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) { - if (nodeTypesInfo.containsKey(nodeType.getKey())) { - NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey()); - List derivedFrom = new ArrayList<>(); - derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName())); - nodeTypeInfo.setDerivedFrom(derivedFrom); - } - } - } - } - } - } - - @SuppressWarnings("unchecked") - private void extractNodeTypeInfo(Map nodeTypesInfo, - List> globalSubstitutes, Map.Entry entry) { - if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) { - if (!isGlobalSubstitute(entry.getKey())) { - String yamlFileContents = new String(entry.getValue()); - Map mappedToscaTemplate = (Map) new Yaml().load(yamlFileContents); - Either substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP); - if (substitutionMappingsEither.isLeft()) { - Map substitutionMappings = (Map) substitutionMappingsEither.left().value(); - if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) { - NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); - nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName())); - nodeTypeInfo.setTemplateFileName(entry.getKey()); - nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate); - nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo); - } - } - } else { - globalSubstitutes.add(entry); - } - } - } - - - @SuppressWarnings("unchecked") - private void markNestedVfc(Map mappedToscaTemplate, Map nodeTypesInfo) { - Either nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP); - if (nodeTemplatesEither.isLeft()) { - Map nodeTemplates = (Map) nodeTemplatesEither.left().value(); - for (Entry nodeTemplateEntry : nodeTemplates.entrySet()) { - Map nodeTemplate = (Map) nodeTemplateEntry.getValue(); - if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (nodeTypesInfo.containsKey(type)) { - NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); - nodeTypeInfo.setNested(true); - } - } - } - } - } - - private boolean isGlobalSubstitute(String fileName) { - return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); - } - - private Either, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either, StorageOperationStatus> csar) { - if (csar.isRight()) { - StorageOperationStatus value = csar.right().value(); - log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - - Either validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils); - if (validateCsarStatus.isRight()) { - ResponseFormat responseFormat = validateCsarStatus.right().value(); - log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - - Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils); - - if (toscaYamlCsarStatus.isRight()) { - ResponseFormat responseFormat = toscaYamlCsarStatus.right().value(); - log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - return toscaYamlCsarStatus; - } - - private Either validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) { - log.trace("validating resource before create"); - Either eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user.copyData(eitherCreator.left().value()); - - // validate user role - Either validateRes = validateUserRole(user, resource, new ArrayList(), AuditingActionEnum.CREATE_RESOURCE, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - // VF / PNF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(resource)) { - Either validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - } - return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); - - } -//resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null - private Either createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, - Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { - - List createdArtifacts = new ArrayList(); - log.trace("************* createResourceFromYaml before parse yaml "); - Either parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - log.trace("************* createResourceFromYaml after parse yaml "); - ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value(); - log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo); - log.trace("************* createResourceFromYaml before create "); - Either createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, - AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, - nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); - log.trace("************* createResourceFromYaml after create "); - if (createdResourceResponse.isRight()) { - ResponseFormat responseFormat = createdResourceResponse.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - return createdResourceResponse; - - } - - public Either, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map mappedToscaTemplate, boolean needLock, - Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, CsarInfo csarInfo) { - - Either tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - if (tosca_version.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - return Either.right(responseFormat); - } - Either, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - Either, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); - Map mapToConvert = new HashMap(); - mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value()); - Resource vfcCreated = null; - if (eitherNodeTypes.isLeft()) { - Iterator> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry nodeType = nodesNameValue.next(); - Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey()); - - if (nodeTypesInfo.containsKey(nodeType.getKey())) { - log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); - Either handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey()); - log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); - if (handleNeatedVfcYaml.isRight()) { - return Either.right(handleNeatedVfcYaml.right().value()); - } - vfcCreated = handleNeatedVfcYaml.left().value(); - } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){ - log.trace("************* Going to create node {}", nodeType.getKey()); - Either, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true); - log.debug("************* Finished to create node {}", nodeType.getKey()); - - if (resourceCreated.isRight()) { - return Either.right(resourceCreated.right().value()); - } - vfcCreated = resourceCreated.left().value().getLeft(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName()); - } - if (vfcCreated != null) { - csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); - } - mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName()); - } - } - return result; - } - - private Either handleNestedVfc(Resource resource, Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, String nodeName) { - - Either handleNestedVfcRes = Either.left(resource); - String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); - Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - - log.debug("************* Going to create node types from yaml {}", yamlName); - Either, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource, - nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); - if (createNodeTypesRes.isRight()) { - log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value()); - return Either.right(createNodeTypesRes.right().value()); - } - log.debug("************* Finished to create node types from yaml {}", yamlName); - - if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { - log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); - } - return handleNestedVfcRes; - } - - private Either handleComplexVfc(Resource resource, Map>> nodesArtifactsToHandle, List createdArtifacts, - Map nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) { - - Either result = null; - Resource oldComplexVfc = null; - Resource newComplexVfc = null; - - Either buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); - if(buildCvfcRes.isRight()){ - log.debug("Failed to validate complex VFC for node {}. ", nodeName); - result = buildCvfcRes; - } - if(result == null){ - newComplexVfc = buildCvfcRes.left().value(); - Either oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); - if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND){ - oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight()); - } - if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){ - log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } else if(oldComplexVfcRes.isLeft()){ - log.debug("validate derived before update"); - Either eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); - if (eitherValidation.isLeft()) { - oldComplexVfc = oldComplexVfcRes.left().value(); - } - } - } - if(result == null){ - result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc); - } - if(result.isLeft()){ - newComplexVfc = result.left().value(); - csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); - log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); - result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true); - if (result.isRight()) { - log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName()); - } - } - if(result.isLeft()){ - csarInfo.getCreatedNodes().put(nodeName, result.left().value()); - csarInfo.getCvfcToCreateQueue().remove(); - } - return result; - } - - private Either handleComplexVfc(Map>> nodesArtifactsToHandle, List createdArtifacts, Map nodesInfo, - CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { - - Either handleComplexVfcRes; - Map mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); - String yamlContent = new String(csarInfo.getCsar().get(yamlName)); - Map newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy())); - markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); - if(oldComplexVfc == null){ - handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName); - if (handleComplexVfcRes.isRight()) { - log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName); - } - } else { - handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); - if (handleComplexVfcRes.isRight()) { - log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName); - } - } - return handleComplexVfcRes; - } - - private Either buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map nodesInfo) { - - Either result = null; - Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); - log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); - - if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){ - csarInfo.getCvfcToCreateQueue().add(nodeName); - } else { - log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName()); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName())); - } - if(result == null){ - result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); - if(result.isRight()){ - log.debug("Failed to validate complex VFC {}. ", complexVfc.getName()); - } - } - return result; - } - - private String getNodeTypeActualName(String fullName) { - String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - return nameWithouNamespacePrefix.substring(resourceType.length()); - } - - private Either, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry nodeNameValue, User user, Map mapToConvert, Resource resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, boolean isNested) { - - Either resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); - if (resourceMetaData.isRight()) { - return Either.right(resourceMetaData.right().value()); - } - String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo); - - Either eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested); - } - - private String buildNodeTypeYaml(Entry nodeNameValue, Map mapToConvert, String nodeResourceType, CsarInfo csarInfo) { - // We need to create a Yaml from each node_types in order to create - // resource from each node type using import normative flow. - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - - Map node = new HashMap<>(); - node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), nodeNameValue.getValue()); - mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); - - return yaml.dumpAsMap(mapToConvert); - } - - public Either validateResourceCreationFromNodeType(Resource resource, User creator) { - - Either validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - return Either.left(true); - } - - public Either, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, - Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); - Function> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator); - return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); - } - - private Either fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) { - UploadResourceInfo resourceMetaData = new UploadResourceInfo(); - - // validate nodetype name prefix - if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { - log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); - return Either.right(responseFormat); - } - - String actualName = this.getNodeTypeActualName(nodeName); - String namePrefix = nodeName.replace(actualName, ""); - String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - - // if we import from csar, the node_type name can be - // org.openecomp.resource.abstract.node_name - in this case we always - // create a vfc - if (resourceType.equals(Constants.ABSTRACT)) { - resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); - } - // validating type - if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { - log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName); - return Either.right(responseFormat); - } - - // Setting name - resourceMetaData.setName(resourceVf.getSystemName() + actualName); - - // Setting type from name - String type = resourceType.toUpperCase(); - resourceMetaData.setResourceType(type); - - resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); - resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); - resourceMetaData.setContactId(user.getUserId()); - resourceMetaData.setVendorName(resourceVf.getVendorName()); - resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); - - // Setting tag - List tags = new ArrayList<>(); - tags.add(resourceMetaData.getName()); - resourceMetaData.setTags(tags); - - // Setting category - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List categories = new ArrayList<>(); - categories.add(category); - resourceMetaData.setCategories(categories); - - return Either.left(resourceMetaData); - } - - private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map nodesInfo) { - Resource cvfc = new Resource(); - NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); - cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); - cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); - cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); - cvfc.setResourceType(ResourceTypeEnum.CVFC); - cvfc.setAbstract(true); - cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); - cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); - cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); - cvfc.setContactId(csarInfo.getModifier().getUserId()); - cvfc.setCreatorUserId(csarInfo.getModifier().getUserId()); - cvfc.setVendorName(resourceVf.getVendorName()); - cvfc.setVendorRelease(resourceVf.getVendorRelease()); - cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); - cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft()); - cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); - - List tags = new ArrayList<>(); - tags.add(cvfc.getName()); - cvfc.setTags(tags); - - CategoryDefinition category = new CategoryDefinition(); - category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); - SubCategoryDefinition subCategory = new SubCategoryDefinition(); - subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); - category.addSubCategory(subCategory); - List categories = new ArrayList<>(); - categories.add(category); - cvfc.setCategories(categories); - - cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); - cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); - cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - - return cvfc; - } - - private String buildCvfcName(String resourceVfName, String nodeName) { - String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); - return addCvfcSuffixToResourceName(resourceName); - } - - private Either createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, - List createdArtifacts, String topologyTemplateYaml, Map nodeTypesInfo, - CsarInfo csarInfo, Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { - - boolean result = true; - List nodeTypesNewCreatedArtifacts = new ArrayList<>(); - - if (shouldLock) { - Either lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - return Either.right(responseFormat); - } - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - log.trace("************* createResourceFromYaml before full create resource {}", yamlName); - Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); - if (genericResourceEither.isRight()) { - result = false; - return genericResourceEither; - } - Either createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction); - log.trace("************* createResourceFromYaml after full create resource {}", yamlName); - if (createResourcesEither.isRight()) { - result = false; - return createResourcesEither; - } - resource = createResourcesEither.left().value(); - // add groups to resource - log.trace("************* Going to add inputs from yaml {}", yamlName); - if (resource.shouldGenerateInputs()) - generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); - - Map inputs = parsedToscaYamlInfo.getInputs(); - Either createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction); - if (createInputsOnResource.isRight()) { - result = false; - return createInputsOnResource; - } - resource = createInputsOnResource.left().value(); - log.trace("************* Finish to add inputs from yaml {}", yamlName); - - Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances(); - log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); - - createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName); - log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); - if (createResourcesEither.isRight()) { - result = false; - return createResourcesEither; - } - - resource = createResourcesEither.left().value(); - // validate update vf module group names - Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); - if (validateUpdateVfGroupNamesRes.isRight()) { - result = false; - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - // add groups to resource - Map groups; - log.trace("************* Going to add groups from yaml {}", yamlName); - - if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { - groups = validateUpdateVfGroupNamesRes.left().value(); - } else { - groups = parsedToscaYamlInfo.getGroups(); - } - Either createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups); - if (createGroupsOnResource.isRight()) { - result = false; - return createGroupsOnResource; - } - resource = createGroupsOnResource.left().value(); - log.trace("************* Finished to add groups from yaml {}", yamlName); - - log.trace("************* Going to add artifacts from yaml {}", yamlName); - - if(resource.getResourceType() == ResourceTypeEnum.CVFC){ - if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){ - Either, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - } else { - Either createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false, - inTransaction); - log.trace("************* Finished to add artifacts from yaml {}", yamlName); - if (createdCsarArtifactsEither.isRight()) { - result = false; - return createdCsarArtifactsEither; - } - resource = createdCsarArtifactsEither.left().value(); - } - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null); - ASDCKpiApi.countCreatedResourcesKPI(); - return Either.left(resource); - - } finally { - if (!inTransaction) { - if (!result) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { - createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); - log.debug("component and all its artifacts were deleted, id = {}", resource.getName()); - } - - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - if (shouldLock) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - } - - private Either createGroupsOnResource(Resource resource, User user, Map groups) { - if (groups != null && !groups.isEmpty()) { - Either, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource); - - if (mergeGroupsUsingResource.isRight()) { - log.debug("Failed to prepare groups for creation"); - return Either.right(mergeGroupsUsingResource.right().value()); - } - List groupsAsList = mergeGroupsUsingResource.left().value(); - Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); - } - } else { - return Either.left(resource); - } - Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either updateGroupsOnResource(Resource resource, User user, Map groups) { - if (groups != null && false == groups.isEmpty()) { - List groupsFromResource = resource.getGroups(); - Either, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource); - - if (mergeGroupsUsingResource.isRight()) { - log.debug("Failed to prepare groups for creation"); - return Either.right(mergeGroupsUsingResource.right().value()); - } - List groupsAsList = mergeGroupsUsingResource.left().value(); - List groupsToUpdate = new ArrayList(); - List groupsToDelete = new ArrayList(); - List groupsToCreate = new ArrayList(); - if (groupsFromResource != null && !groupsFromResource.isEmpty()) { - for (GroupDefinition group : groupsAsList) { - Optional op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); - if (op.isPresent()) { - GroupDefinition groupToUpdate = op.get(); - groupToUpdate.setMembers(group.getMembers()); - groupsToUpdate.add(groupToUpdate); - } else { - groupsToCreate.add(group); - } - } - for (GroupDefinition group : groupsFromResource) { - Optional op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); - if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { - - groupsToDelete.add(group); - } - - } - } else - groupsToCreate.addAll(groupsAsList); - Either, ResponseFormat> prepareGroups = null; - if (!groupsToCreate.isEmpty()) { - - if (groupsFromResource != null && !groupsFromResource.isEmpty()) { - prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); - } else { - prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate); - } - - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - if (!groupsToDelete.isEmpty()) { - prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { - prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - - } else { - return Either.left(resource); - } - - Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either createInputsOnResource(Resource resource, User user, Map inputs, boolean inTransaction) { - List resourceProperties = resource.getInputs(); - if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) { - - Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource); - if (createInputs.isRight()) { - return Either.right(createInputs.right().value()); - } - } else { - return Either.left(resource); - } - - Either updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (updatedResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(updatedResource.left().value()); - } - - private Either, ResponseFormat> updateGroupMembersUsingResource(Map groups, Resource component) { - - List result = new ArrayList<>(); - - List componentInstances = component.getComponentInstances(); - - if (groups != null) { - Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); - if (validateCyclicGroupsDependencies.isRight()) { - return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies); - } - for (Entry entry : groups.entrySet()) { - String groupName = entry.getKey(); - - GroupDefinition groupDefinition = entry.getValue(); - - GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); - updatedGroupDefinition.setMembers(null); - - // get the members of the group - Map members = groupDefinition.getMembers(); - if (members != null) { - Set compInstancesNames = members.keySet(); - - if (componentInstances == null || true == componentInstances.isEmpty()) { - String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); - } - // Find all component instances with the member names - Map memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); - memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> ""))); - Map relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue())); - - if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { - - List foundMembers = new ArrayList<>(); - if (relevantInstances != null) { - foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList()); - } - compInstancesNames.removeAll(foundMembers); - String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); - log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component))); - } - - updatedGroupDefinition.setMembers(relevantInstances); - } - - result.add(updatedGroupDefinition); - } - } - return Either.left(result); - } - - /** - * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A - * - * @param allGroups - * @return - */ - private Either validateCyclicGroupsDependencies(Map allGroups) { - - Either result = Either.left(true); - try { - Iterator> allGroupsItr = allGroups.entrySet().iterator(); - while (allGroupsItr.hasNext() && result.isLeft()) { - Entry groupAEntry = allGroupsItr.next(); - // Fetches a group member A - String groupAName = groupAEntry.getKey(); - // Finds all group members in group A - Set allGroupAMembersNames = new HashSet<>(); - fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); - // If A is a group member of itself found cyclic dependency - if (allGroupAMembersNames.contains(groupAName)) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); - result = Either.right(responseFormat); - } - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - result = Either.right(responseFormat); - log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); - } - return result; - } - - /** - * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group. - * - * @param groupName - * @param allGroups - * @param allGroupMembers - * @return - */ - private void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, Set allGroupMembers) { - - // Found Cyclic dependency - if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { - return; - } - GroupDefinition groupDefinition = allGroups.get(groupName); - // All Members Of Current Group Resource Instances & Other Groups - Set currGroupMembers = groupDefinition.getMembers().keySet(); - // Filtered Members Of Current Group containing only members which - // are groups - List currGroupFilteredMembers = currGroupMembers.stream(). - // Keep Only Elements of type group and not Resource Instances - filter(innerGroupName -> allGroups.containsKey(innerGroupName)). - // Add Filtered Elements to main Set - peek(innerGroupName -> allGroupMembers.add(innerGroupName)). - // Collect results - collect(Collectors.toList()); - - // Recursively call the method for all the filtered group members - for (String innerGroupName : currGroupFilteredMembers) { - fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); - } - - } - - private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map allGroups, Set allGroupMembers) { - - boolean stop = false; - // In Case Not Group Stop - if (!allGroups.containsKey(groupName)) { - stop = true; - } - // In Case Group Has no members stop - if (!stop) { - GroupDefinition groupDefinition = allGroups.get(groupName); - stop = MapUtils.isEmpty(groupDefinition.getMembers()); - - } - // In Case all group members already contained stop - if (!stop) { - final Set allMembers = allGroups.get(groupName).getMembers().keySet(); - Set membersOfTypeGroup = allMembers.stream(). - // Filter In Only Group members - filter(innerGroupName -> allGroups.containsKey(innerGroupName)). - // Collect - collect(Collectors.toSet()); - stop = allGroupMembers.containsAll(membersOfTypeGroup); - } - return stop; - } - - private Either createRIAndRelationsFromYaml(String yamlName, Resource resource, Map uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum, - String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, CsarInfo csarInfo, Map>> nodeTypesArtifactsToCreate, - String nodeName) { - - Either result; - Either createResourcesInstancesEither; - - log.debug("************* Going to create all nodes {}", yamlName); - Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName); - log.debug("************* Finished to create all nodes {}", yamlName); - if (createdResourcesFromdNodeTypeMap.isRight()) { - log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value()); - return Either.right(createdResourcesFromdNodeTypeMap.right().value()); - } - - log.debug("************* Going to create all resource instances {}", yamlName); - createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes()); - - log.debug("************* Finished to create all resource instances {}", yamlName); - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); - result = createResourcesInstancesEither; - return createResourcesInstancesEither; - } - resource = createResourcesInstancesEither.left().value(); - log.debug("************* Going to create all relations {}", yamlName); - createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap); - - log.debug("************* Finished to create all relations {}", yamlName); - - if (createResourcesInstancesEither.isRight()) { - log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value()); - result = createResourcesInstancesEither; - return result; - } else { - resource = createResourcesInstancesEither.left().value(); - } - - log.debug("************* Going to create positions {}", yamlName); - Either, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); - log.debug("************* Finished to set positions {}", yamlName); - result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource); - - return result; - } - - private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, List artifactsToAdd) { - List vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList()); - artifactsToAdd.stream().forEach(a -> { - if (!vfcArtifactNames.contains(a.getArtifactName())) { - vfcArtifacts.add(a); - } else { - log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName()); - } - }); - - } - - @SuppressWarnings("unchecked") - private Either, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock, - Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, CsarInfo csarInfo, String nodeName) { - - Either, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); - for (Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { - if (nodeTypeEntry.getValue().isNested()) { - - Either createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); - log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); - if (createResourceFromYaml.isRight()) { - return Either.right(createResourceFromYaml.right().value()); - } - } - } - - Map mappedToscaTemplate = null; - if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){ - mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); - } - if(MapUtils.isEmpty(mappedToscaTemplate)){ - mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); - } - - Either, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); - if (createdNodeTypeFromMainTemplateEither.isRight()) { - ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - // add the created node types to the cache although they are not in the - // graph. - csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource)); - - return result; - } - - private Either handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, - boolean inTransaction) { - - if (csarInfo.getCsar() != null) { - String vendorLicenseModelId = null; - String vfLicenseModelId = null; - - if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) { - Map deploymentArtifactsMap = resource.getDeploymentArtifacts(); - if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { - for (Entry artifactEntry : deploymentArtifactsMap.entrySet()) { - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) - vendorLicenseModelId = artifactEntry.getValue().getUniqueId(); - if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) - vfLicenseModelId = artifactEntry.getValue().getUniqueId(); - } - } - - } - // Specific Behavior for license artifacts - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction); - createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction); - - Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); - if (eitherCreateResult.isRight()) { - return Either.right(eitherCreateResult.right().value()); - } - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - resource = eitherGerResource.left().value(); - - Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); - if (artifacsMetaCsarStatus.isLeft()) { - - String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); - String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); - Either createArtifactsFromCsar = Either.left(resource); - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) - createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - else - createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); - if (createArtifactsFromCsar.isRight()) { - log.debug("Couldn't create artifacts from artifacts.meta"); - return Either.right(createArtifactsFromCsar.right().value()); - } - - resource = createArtifactsFromCsar.left().value(); - } else { - List groupsToDelete = resource.getGroups(); - - if (groupsToDelete != null && !groupsToDelete.isEmpty()) { - Set artifactsToDelete = new HashSet(); - - for (String artifactId : artifactsToDelete) { - Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, - resource, null, null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - log.debug("Couldn't delete artifact {}", artifactId); - return Either.right(handleDelete.right().value()); - } - } - Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - - return Either.right(responseFormat); - - } - resource = eitherGetResource.left().value(); - } - } - } - return Either.left(resource); - } - - private Either createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType, - ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List createdArtifacts, boolean shouldLock, - boolean inTransaction) { - byte[] artifactFileBytes = null; - - if (csarInfo.getCsar().containsKey(artifactPath)) { - artifactFileBytes = csarInfo.getCsar().get(artifactPath); - } - Either result = Either.left(true); - if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) { - if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) { - Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null, - null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - result = Either.right(handleDelete.right().value()); - } - return result; - } - - if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) { - operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create); - } - - } - if (artifactFileBytes != null) { - Map vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null); - Either, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction); - addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); - if (eitherNonMetaArtifacts.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING); - return Either.right(eitherNonMetaArtifacts.right().value()); - } - } - return result; - } - - private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List createdArtifacts, Either, ResponseFormat> eitherNonMetaArtifacts) { - if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) { - Either eitherResult = eitherNonMetaArtifacts.left().value(); - if (eitherResult.isLeft()) { - createdArtifacts.add(eitherResult.left().value()); - } - } - } - - private Either, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) { - - String jsonStr = gson.toJson(json); - - String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr); - ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class); - String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId(); - Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId, - artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false); - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - return Either.left(uploadArtifactToService.left().value()); - } - - public Either updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List createdNewArtifacts, - boolean shouldLock, boolean inTransaction) { - - Either>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - - List groups = resource.getGroups(); - Map deplymentArtifact = resource.getDeploymentArtifacts(); - List createdDeplymentArtifactsAfterDelete = new ArrayList(); - if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { - for (Entry entry : deplymentArtifact.entrySet()) { - createdDeplymentArtifactsAfterDelete.add(entry.getValue()); - } - } - int labelCounter = createdDeplymentArtifactsAfterDelete.size(); - - if (deplymentArtifact == null || deplymentArtifact.isEmpty()) { - if (groups != null && !groups.isEmpty()) { - for (GroupDefinition group : groups) { - if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) { - log.debug("failed to update artifacts from csar. List of emty but group not empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } - } - return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction); - } - - // find master in group - Map>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact); - - ////////////////////////////////////// create set parsed - ////////////////////////////////////// artifacts/////////////////////////////////////////// - Map> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value(); - - Map> parsedGroup = new HashMap>(); - List artifactsWithoutGroups = null; - if(parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)){ - artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT); - parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT); - } - Collection> parsedArifactsCollection = parsedArtifactsMap.values(); - for (List parsedGroupTemplateList : parsedArifactsCollection) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - if(parsedGroupTemplate.getGroupName() != null){ - parsedGroupTemplate.setGroupName(""); - Set parsedArtifactsNames = new HashSet(); - parsedArtifactsNames.add(parsedGroupTemplate); - List relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { - createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames); - } - parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames); - }else{ - List arrtifacts = new ArrayList(); - arrtifacts.add(parsedGroupTemplate); - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - - } - } - - } - - ///////////////////////////////// find artifacts to - ///////////////////////////////// delete//////////////////////////////////////////////////// - - Set artifactsToDelete = new HashSet(); - Map> groupToDelete = new HashMap>(); - - Set jsonMasterArtifacts = parsedGroup.keySet(); - Map mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete); - - // Set deletedArtifactsName = new HashSet(); - Either, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete); - if (deletedArtifactsEither.isRight()) { - log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value()); - - return Either.right(deletedArtifactsEither.right().value()); - - } - List deletedArtifacts = deletedArtifactsEither.left().value(); - - // need to update resource if we updated artifacts - if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) { - for (ArtifactDefinition deletedArtifact : deletedArtifacts) { - ArtifactDefinition artToRemove = null; - for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) { - if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) { - artToRemove = artFromResource; - break; - } - } - if (artToRemove != null) - createdDeplymentArtifactsAfterDelete.remove(artToRemove); - - } - } - - ////////////// dissociate, associate or create - ////////////// artifacts//////////////////////////// - Either assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete, - mergedgroup, deletedArtifacts); - groups = resource.getGroups(); - if (assDissotiateEither.isRight()) { - log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value()); - - return Either.right(assDissotiateEither.right().value()); - - } - resource = assDissotiateEither.left().value(); - deplymentArtifact = resource.getDeploymentArtifacts(); - createdDeplymentArtifactsAfterDelete.clear(); - if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) { - for (Entry entry : deplymentArtifact.entrySet()) { - createdDeplymentArtifactsAfterDelete.add(entry.getValue()); - } - } - - - - // update vfModule names - Set groupForAssociateWithMembers = mergedgroup.keySet(); - if (groups != null && !groups.isEmpty()) { - Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction); - if (validateUpdateVfGroupNamesRes.isRight()) { - return Either.right(validateUpdateVfGroupNamesRes.right().value()); - } - List heatGroups = null; - - heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - ; - - for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) { - - if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) { - updatedGroupDef.getMembers().clear(); - } - Map members = new HashMap(); - Set artifactsGroup = new HashSet(); - artifactsGroup.addAll(updatedGroupDef.getArtifacts()); - associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members); - if (!members.isEmpty()) { - updatedGroupDef.setMembers(members); - - } - - - } - - - } - - //////////////// create new artifacts in update - //////////////// flow//////////////////////////// - List newArtifactsGroup = new ArrayList(); - - for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { - ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey(); - boolean isNewGroup = true; - for (Entry>> groupListEntry : groupArtifact.entrySet()) { - Map> groupArtifacts = groupListEntry.getValue(); - Set group = groupArtifacts.keySet(); - for (ArtifactDefinition artifactInfo : group) { - if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) { - parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName()); - isNewGroup = false; - } - } - } - if (isNewGroup) - newArtifactsGroup.add(parsedArtifactMaster); - - } - if (!newArtifactsGroup.isEmpty()) { - Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); - int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups); - Either validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter); - if (validateGroupNamesRes.isRight()) { - return Either.right(validateGroupNamesRes.right().value()); - } - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - - // updatedGroup - if (!groupForAssociateWithMembers.isEmpty()) { - - List groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList()); - - Either, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId); - if (updateVersionEither.isRight()) { - log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value()); - - return Either.right(updateVersionEither.right().value()); - - } - } - if(artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()){ - for(ArtifactTemplateInfo t: artifactsWithoutGroups){ - List arrtifacts = new ArrayList(); - arrtifacts.add(t); - Either resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - }; - } - - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - return Either.left(eitherGerResource.left().value()); - - } - - private Either, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set artifactsToDelete, - Map> groupToDelete) { - List deletedArtifacts = new ArrayList(); - String resourceId = resource.getUniqueId(); - if (!artifactsToDelete.isEmpty()) { - for (ArtifactDefinition artifact : artifactsToDelete) { - String artifactType = artifact.getArtifactType(); - ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType); - if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) { - Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, - null, null, shouldLock, inTransaction); - if (handleDelete.isRight()) { - return Either.right(handleDelete.right().value()); - } - - deletedArtifacts.add(handleDelete.left().value().left().value()); - } - - } - } - if (!groupToDelete.isEmpty()) { - log.debug("try to delete group"); - List groupDefinitionstoDelete = new ArrayList<>(); - List groups = resource.getGroups(); - for (Entry> deleteGroup : groupToDelete.entrySet()) { - Optional op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny(); - if (op.isPresent()) { - groupDefinitionstoDelete.add(op.get()); - } - - } - if (!groupDefinitionstoDelete.isEmpty()) { - Either, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete); - if (prepareGroups.isRight()) { - return Either.right(prepareGroups.right().value()); - } - } - } - return Either.left(deletedArtifacts); - } - - private Either associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List createdNewArtifacts, int labelCounter, boolean shouldLock, - boolean inTransaction, List createdDeplymentArtifactsAfterDelete, Map mergedgroup, List deletedArtifacts) { - Map> artifactsToAssotiate = new HashMap>(); - Map>> artifactsToUpdateMap = new HashMap>>(); - Either resEither = Either.left(resource); - for (Entry entry : mergedgroup.entrySet()) { - List dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts); - GroupDefinition grDef = entry.getKey(); - if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) { - for (ArtifactDefinition art : dissArtifactsInGroup) { - grDef.getArtifacts().remove(art.getUniqueId()); - grDef.getArtifactsUuid().remove(art.getArtifactUUID()); - } - } - - List newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup(); - if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) - artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup); - - List> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup(); - if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) - artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate); - } - - if (!artifactsToUpdateMap.isEmpty()) { - List updatedArtifacts = new ArrayList(); - for (Entry>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) { - List> artifactsToUpdateList = artifactsToUpdateEntry.getValue(); - GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey(); - - for (ImmutablePair artifact : artifactsToUpdateList) { - String prevUUID = artifact.getKey().getArtifactUUID(); - String prevId = artifact.getKey().getUniqueId(); - String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey()); - Either updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts, - artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction); - if (updateArtifactEither.isRight()) { - log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value()); - resEither = Either.right(updateArtifactEither.right().value()); - return resEither; - } - ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value(); - if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) { - groupToUpdate.getArtifacts().remove(prevId); - groupToUpdate.getArtifactsUuid().remove(prevUUID); - groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId()); - groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID()); - } - Optional op = updatedArtifacts.stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())).findAny(); - if (op.isPresent()) { - ArtifactDefinition artifactInfoHeatEnv = op.get(); - groupToUpdate.getArtifacts().remove(prevHeatEnvId); - groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId()); - } - - } - } - } - - for (Entry> associateEntry : artifactsToAssotiate.entrySet()) { - List associatedArtifact = associateEntry.getValue(); - Set arifactsUids = new HashSet(); - Set arifactsUuids = new HashSet(); - for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try - // to - // find - // artifact - // in - // resource - boolean isCreate = true; - for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) { - if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) { - arifactsUids.add(createdArtifact.getUniqueId()); - arifactsUuids.add(createdArtifact.getArtifactUUID()); - isCreate = false; - String heatEnvId = checkAndGetHeatEnvId(createdArtifact); - if (!heatEnvId.isEmpty()) { - arifactsUids.add(heatEnvId); - Optional op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny(); - if (op.isPresent()) { - this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType()); - - } - } - - break; - } - - } - if (isCreate) { // check if already created - for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) { - if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) { - arifactsUids.add(createdNewArtifact.getUniqueId()); - arifactsUuids.add(createdNewArtifact.getArtifactUUID()); - isCreate = false; - String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact); - if (!heatEnvId.isEmpty()) { - arifactsUids.add(heatEnvId); - } - break; - } - } - } - - if (isCreate) { - Either createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction); - if (createArtifactEither.isRight()) { - resEither = Either.right(createArtifactEither.right().value()); - return resEither; - } - ArtifactDefinition createdArtifact = createArtifactEither.left().value(); - arifactsUids.add(createdArtifact.getUniqueId()); - arifactsUuids.add(createdArtifact.getArtifactUUID()); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId(); - arifactsUids.add(heatEnvId); - } - } - - } - if (arifactsUids.size() > 0) { - List artifactsToAssociate = new ArrayList(); - artifactsToAssociate.addAll(arifactsUids); - GroupDefinition assotiateGroup = associateEntry.getKey(); - assotiateGroup.getArtifacts().addAll(arifactsUids); - assotiateGroup.getArtifactsUuid().addAll(arifactsUuids); - } - } - - - - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreArtifacts(false); - parametersView.setIgnoreGroups(false); - - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - resEither = Either.right(responseFormat); - return resEither; - - } - resEither = Either.left(eitherGerResource.left().value()); - return resEither; - } - - private Map mergeGroupInUpdateFlow(Map>> groupArtifact, Map> parsedGroup, - Set artifactsToDelete, Map> groupToDelete, Set jsonMasterArtifacts, List createdDeplymentArtifacts) { - Map mergedgroup = new HashMap(); - for (Entry>> groupListEntry : groupArtifact.entrySet()) { - Map> createdArtifactMap = groupListEntry.getValue(); - boolean isNeedToDeleteGroup = true; - List listToDelete = null; - for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) { - listToDelete = createdArtifactMap.get(maserArtifact); - for (ArtifactDefinition artToDelete : listToDelete) { - findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts); - } - if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) { - GroupDefinition group = groupListEntry.getKey(); - for (ArtifactDefinition artifactDefinition : artifactsToDelete) { - if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) { - group.getArtifacts().remove(artifactDefinition.getUniqueId()); - - } - if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) { - group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID()); - - } - } - - } - - for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) { - if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) { - MergedArtifactInfo mergedGroup = new MergedArtifactInfo(); - mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact); - mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact)); - mergedgroup.put(groupListEntry.getKey(), mergedGroup); - isNeedToDeleteGroup = false; - - } - } - - } - if (isNeedToDeleteGroup) { - groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete); - } - - } - return mergedgroup; - } - - private void findArtifactToDelete(Map> parsedGroup, Set artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact, - List createdDeplymentArtifacts) { - boolean isNeedToDeleteArtifact = true; - String artifactType = artifact.getArtifactType(); - ArtifactDefinition generatedFromArt = null; - if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) { - Optional op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny(); - if (op.isPresent()) - generatedFromArt = op.get(); - - } - - for (Entry> parsedGroupSetEntry : parsedGroup.entrySet()) { - Set artifactsNames = parsedGroupSetEntry.getValue(); - for (ArtifactTemplateInfo template : artifactsNames) { - if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) { - isNeedToDeleteArtifact = false; - break; - - } else { - if (generatedFromArt != null) { - if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) { - isNeedToDeleteArtifact = false; - break; - } - } - } - } - - } - if (isNeedToDeleteArtifact) { - artifactsToDelete.add(artifact); - - } - } - - private Map>> findMasterArtifactInGroup(List groups, Map deplymentArtifact) { - Map>> groupArtifact = new HashMap>>(); - - for (GroupDefinition group : groups) { - Map> gupsMap = new HashMap>(); - List artifacts = new ArrayList(); - List artifactsList = group.getArtifacts(); - if (artifactsList != null && !artifactsList.isEmpty()) { - - ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList); - if (masterArtifact != null) - gupsMap.put(masterArtifact, artifacts); - groupArtifact.put(group, gupsMap); - - } - } - return groupArtifact; - } - - private void createArtifactsGroupSet(List parsedGroupTemplateList, Set parsedArtifactsName) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - parsedArtifactsName.add(parsedGroupTemplate); - List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); - } - } - } - - public Either createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List createdArtifacts, - boolean shouldLock, boolean inTransaction) { - - log.debug("parseResourceArtifactsInfoFromFile start"); - Either>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier()); - if (parseResourceInfoFromYamlEither.isRight()) { - ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return Either.right(responseFormat); - } - log.debug("parseResourceArtifactsInfoFromFile end"); - - log.debug("createResourceArtifacts start"); - Either respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction); - if (respStatus.isRight()) { - return respStatus; - } - log.debug("createResourceArtifacts end"); - log.debug("getResource start"); - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("getResource end"); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - return Either.left(eitherGerResource.left().value()); - - } - - private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List artifactsTemplateList, - List createdNewArtifacts, List artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) { - Either resStatus = Either.left(resource); - List createdGroups = resource.getGroups(); - List heatGroups = null; - if (createdGroups != null && !createdGroups.isEmpty()) { - heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - } - - List needToAdd = new ArrayList<>(); - for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { - String groupName = groupTemplateInfo.getGroupName(); - Set artifactsGroup = new HashSet(); - Set artifactsUUIDGroup = new HashSet(); - - resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - if(groupName != null && !groupName.isEmpty()){ - Map members = new HashMap(); - associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members); - - List artifactsList = new ArrayList(artifactsGroup); - List artifactsUUIDList = new ArrayList(artifactsUUIDGroup); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setName(groupName); - groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); - groupDefinition.setArtifacts(artifactsList); - groupDefinition.setArtifactsUuid(artifactsUUIDList); - - if (!members.isEmpty()) - groupDefinition.setMembers(members); - - List properties = new ArrayList(); - GroupProperty prop = new GroupProperty(); - prop.setName(Constants.IS_BASE); - prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - - List createdArtifacts = new ArrayList<>(); - createdArtifacts.addAll(createdNewArtifacts); - createdArtifacts.addAll(artifactsFromResource); - Either getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); - if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); - } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); - groupDefinition.convertFromGroupProperties(properties); - - needToAdd.add(groupDefinition); - } - } - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); - if (component.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - resource = component.left().value(); - - Either, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd); - if (addGroups.isRight()) - return Either.right(addGroups.right().value()); - - return resStatus; - } - - private Either createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set artifactsGroup, Set artifactsUUIDGroup, - ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, List artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) { - Either resStatus = Either.left(resource); - String artifactFileName = artifactTemplateInfo.getFileName(); - String artifactUid = ""; - String artifactUUID = ""; - String artifactEnvUid = ""; - boolean alreadyExist = false; - - // check if artifacts already exist - if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) { - for (ArtifactDefinition artifactFromResource : artifactsFromResource) { - if (artifactFromResource.getArtifactName().equals(artifactFileName)) { - artifactUid = artifactFromResource.getUniqueId(); - artifactUUID = artifactFromResource.getArtifactUUID(); - if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource); - break; - } - - } - - } - if (!alreadyExist) { - for (ArtifactDefinition createdArtifact : createdArtifacts) { - if (createdArtifact.getArtifactName().equals(artifactFileName)) { - artifactUid = createdArtifact.getUniqueId(); - artifactUUID = createdArtifact.getArtifactUUID(); - - if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); - break; - } - - } - } - // if not exist need to create - if (!alreadyExist) { - - Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (newArtifactEither.isRight()) { - resStatus = Either.right(newArtifactEither.right().value()); - return resStatus; - } - ArtifactDefinition newArtifact = newArtifactEither.left().value(); - artifactUid = newArtifact.getUniqueId(); - artifactUUID = newArtifact.getArtifactUUID(); - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); - } - } - - artifactsGroup.add(artifactUid); - artifactsUUIDGroup.add(artifactUUID); - if (!artifactEnvUid.isEmpty()) { - artifactsGroup.add(artifactEnvUid); - } - - List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null) { - for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - return resStatus; - } - - private Either createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map> artifactsMap, AuditingActionEnum createResource, - List createdArtifacts, boolean shouldLock, boolean inTransaction) { - - Either resStatus = Either.left(resource); - - Collection> arifactsCollection = artifactsMap.values(); - - for (List groupTemplateList : arifactsCollection) { - if (groupTemplateList != null) { - resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - - return resStatus; - - } - - private Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) { - - Either resStatus = null; - Map>> collectedWarningMessages = new HashMap<>(); - - try { - List artifactPathAndNameList = - // Stream of file paths contained in csar - csarInfo.getCsar().entrySet().stream() - // Filter in only VF artifact path location - .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // Validate and add warnings - .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)) - // Filter in Non Warnings - .filter(e -> e.isLeft()) - // Convert from Either to NonMetaArtifactInfo - .map(e -> e.left().value()) - // collect to List - .collect(Collectors.toList()); - - Either responseFormatEither = validateArtifactNames(artifactPathAndNameList); - if (responseFormatEither.isRight()) { - return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value())); - } - - - EnumMap> vfCsarArtifactsToHandle = null; - - if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { - vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList); - } else { - Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier()); - - if (findVfCsarArtifactsToHandleRes.isRight()) { - resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); - } - if (resStatus == null) { - vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); - } - } - if (resStatus == null && vfCsarArtifactsToHandle != null) { - for (Entry> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) { - - Optional optionalCreateInDBError = - // Stream of artifacts to be created - currArtifactOperationPair.getValue().stream() - // create each artifact - .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock, - inTransaction)) - // filter in only error - .filter(e -> e.isRight()). - // Convert the error from either to ResponseFormat - map(e -> e.right().value()). - // Check if an error occurred - findAny(); - // Error found on artifact Creation - if (optionalCreateInDBError.isPresent()) { - resStatus = Either.right(optionalCreateInDBError.get()); - break; - } - } - } - if (resStatus == null) { - resStatus = Either.left(resource); - } - } catch (Exception e) { - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); - } finally { - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - return resStatus; - } - - private Either validateArtifactNames(List artifactPathAndNameList) { - Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); - for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { - if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { - return Either.right(nonMetaArtifactInfo.getArtifactName()); - } - } - return Either.left(true); - } - - - private Either>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List artifactPathAndNameList, User user) { - - List existingArtifacts = new ArrayList<>(); - // collect all Deployment and Informational artifacts of VF - if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); - } - if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { - existingArtifacts.addAll(resource.getArtifacts().values()); - } - existingArtifacts = existingArtifacts.stream() - // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta - .filter(this::isNonMetaArtifact).collect(Collectors.toList()); - - List artifactsToIgnore = new ArrayList<>(); - // collect IDs of Artifacts of VF which belongs to any group - if (resource.getGroups() != null) { - resource.getGroups().stream().forEach(g -> { - if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) - artifactsToIgnore.addAll(g.getArtifacts()); - }); - } - existingArtifacts = existingArtifacts.stream() - // filter artifacts which belongs to any group - .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList()); - return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); - } - - private boolean isNonMetaArtifact(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { - result = false; - } - return result; - } - - private boolean isValidArtifactType(ArtifactDefinition artifact) { - boolean result = true; - if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { - result = false; - } - return result; - } - - private Either createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List artifactsTemplateList, List createdArtifacts, - int labelCounter, boolean shouldLock, boolean inTransaction) { - Either resStatus = Either.left(resource); - List createdGroups = resource.getGroups(); - List heatGroups = null; - if (createdGroups != null && !createdGroups.isEmpty()) { - - // List collect = resources.stream().flatMap( e -> - // e.getArtifacts().stream()).filter(p -> - // relevantArtifactTypes.contains(p.getArtifactType() - // )).collect(Collectors.toList()); - // List heatGroups = createdGroups.stream().filter( - // e -> e.getProperties().stream().filter(p -> - // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList()); - heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList()); - ; - } - List needToCreate = new ArrayList<>(); - for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) { - String groupName = groupTemplateInfo.getGroupName(); - Set artifactsGroup = new HashSet(); - Set artifactsUUIDGroup = new HashSet(); - - log.debug("createDeploymentArtifactsFromCsar start"); - resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction); - log.debug("createDeploymentArtifactsFromCsar end"); - if (resStatus.isRight()) - return resStatus; - if(groupName != null && !groupName.isEmpty()){ - Map members = new HashMap(); - associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members); - - List artifactsList = new ArrayList(artifactsGroup); - List artifactsUUIDList = new ArrayList(artifactsUUIDGroup); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setName(groupName); - groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE); - groupDefinition.setArtifacts(artifactsList); - groupDefinition.setArtifactsUuid(artifactsUUIDList); - - if (!members.isEmpty()) - groupDefinition.setMembers(members); - List properties = new ArrayList(); - GroupProperty prop = new GroupProperty(); - prop.setName(Constants.IS_BASE); - prop.setValue(Boolean.toString(groupTemplateInfo.isBase())); - properties.add(prop); - Either getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true); - if (getLatestGroupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value()))); - } - properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value()); - groupDefinition.convertFromGroupProperties(properties); - log.debug("createGroup start"); - - needToCreate.add(groupDefinition); - } - } - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreGroups(false); - - componentParametersView.setIgnoreComponentInstances(false); - - Either component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView); - if (component.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - Either, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate); - if (createGroups.isRight()) { - return Either.right(createGroups.right().value()); - } - - return resStatus; - } - - public List createVfModuleAdditionalProperties(boolean isBase, String moduleName, List properties, List deploymentArtifacts, List artifactsInGroup, GroupTypeDefinition groupType) { - Map vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties(); - vfModuleProperties.entrySet().forEach(p -> { - GroupProperty prop = new GroupProperty(); - prop.setName(p.getKey()); - if (isBase) { - prop.setValue(p.getValue().getForBaseModule()); - prop.setDefaultValue(p.getValue().getForBaseModule()); - } else { - prop.setValue(p.getValue().getForNonBaseModule()); - prop.setDefaultValue(p.getValue().getForNonBaseModule()); - } - properties.add(prop); - - }); - GroupProperty proplabel = new GroupProperty(); - proplabel.setName("vf_module_label"); - - Matcher matcher = pattern.matcher(moduleName); - - if (matcher.find()) { - proplabel.setValue(matcher.group(1)); - proplabel.setDefaultValue(matcher.group(1)); - } else { - proplabel.setValue(moduleName); - proplabel.setDefaultValue(moduleName); - } - properties.add(proplabel); - - GroupProperty propvolume = new GroupProperty(); - propvolume.setName("volume_group"); - boolean isVolume = false; - for (String artifactId : artifactsInGroup) { - ArtifactDefinition artifactDef = null; - artifactDef = findArtifactInList(deploymentArtifacts, artifactId); - if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { - isVolume = true; - break; - } - } - propvolume.setValue(String.valueOf(isVolume)); - propvolume.setDefaultValue(String.valueOf(isVolume)); - properties.add(propvolume); - mergeWithGroupTypeProperties(properties, groupType.getProperties()); - return properties; - } - - private void mergeWithGroupTypeProperties(List properties, List groupTypeProperties) { - - Map propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - for (PropertyDefinition groupTypeProperty : groupTypeProperties) { - if (!propertiesMap.containsKey(groupTypeProperty.getName())) { - properties.add(new GroupProperty(groupTypeProperty)); - } - } - } - - private ArtifactDefinition findArtifactInList(List createdArtifacts, String artifactId) { - for (ArtifactDefinition artifact : createdArtifacts) { - if (artifact.getUniqueId().equals(artifactId)) { - return artifact; - } - } - return null; - } - - private void associateMembersToArtifacts(List createdArtifacts, List artifactsFromResource, List heatGroups, Set artifactsGroup, Map members) { - if (heatGroups != null && !heatGroups.isEmpty()) { - for (GroupDefinition heatGroup : heatGroups) { - List grpoupProps = heatGroup.convertToGroupProperties(); - if (grpoupProps != null) { - Optional op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny(); - if (op.isPresent()) { - GroupProperty prop = op.get(); - String heatFileNAme = prop.getValue(); - if (null == heatFileNAme || heatFileNAme.isEmpty()) - continue; - List artifacts = new ArrayList(); - for (String artifactId : artifactsGroup) { - Optional opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); - if (opArt.isPresent()) { - artifacts.add(opArt.get()); - } - if (artifactsFromResource != null) { - opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny(); - if (opArt.isPresent()) { - artifacts.add(opArt.get()); - } - } - } - Optional resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny(); - if (resOp.isPresent()) { - members.putAll(heatGroup.getMembers()); - } - } - } - } - - } - } - - private Either createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set artifactsGroup, Set artifactsUUIDGroup, - ArtifactTemplateInfo artifactTemplateInfo, List createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { - Either resStatus = Either.left(resource); - String artifactFileName = artifactTemplateInfo.getFileName(); - String artifactUid = ""; - String artifactEnvUid = ""; - String artifactUUID = ""; - boolean alreadyExist = false; - - // check if artifacts already exist - for (ArtifactDefinition createdArtifact : createdArtifacts) { - if (createdArtifact.getArtifactName().equals(artifactFileName)) { - artifactUid = createdArtifact.getUniqueId(); - artifactUUID = createdArtifact.getArtifactUUID(); - if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType())); - } - alreadyExist = true; - artifactEnvUid = checkAndGetHeatEnvId(createdArtifact); - break; - } - } - // if not exist need to create - if (!alreadyExist) { - - Either newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (newArtifactEither.isRight()) { - resStatus = Either.right(newArtifactEither.right().value()); - return resStatus; - } - ArtifactDefinition newArtifact = newArtifactEither.left().value(); - artifactUid = newArtifact.getUniqueId(); - artifactUUID = newArtifact.getArtifactUUID(); - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - Either createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource, - resource.getName(), csarInfo.getModifier(), resource, null); - if (createHeatEnvPlaceHolder.isRight()) { - return Either.right(createHeatEnvPlaceHolder.right().value()); - } - artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId(); - } - } - - artifactsGroup.add(artifactUid); - artifactsUUIDGroup.add(artifactUUID); - if (!artifactEnvUid.isEmpty()) { - artifactsGroup.add(artifactEnvUid); - } - - List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null) { - for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) { - resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction); - if (resStatus.isRight()) - return resStatus; - } - } - return resStatus; - } - - private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) { - String artifactEnvUid = ""; - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType()); - if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) { - artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX; - } - return artifactEnvUid; - } - - private Either createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, - List createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) { - final String artifactFileName = artifactTemplateInfo.getFileName(); - Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils); - if (artifactContententStatus.isRight()) { - return Either.right(artifactContententStatus.right().value()); - } - labelCounter += createdArtifacts.size(); - - Map json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter); - - Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), - shoudLock, inTransaction); - - if (uploadArtifactToService.isRight()) - return Either.right(uploadArtifactToService.right().value()); - - ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); - if (currentInfo.getHeatParameters() != null) { - - Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false); - if (updateEnvEither.isRight()) { - log.debug("failed to update parameters to artifact {}", artifactFileName); - return Either.right(updateEnvEither.right().value()); - - } - currentInfo = updateEnvEither.left().value(); - - } - - createdArtifacts.add(currentInfo); - - return Either.left(currentInfo); - - } - - private Either updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo, - List updatedArtifacts, List updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) { - - Either resStatus = null; - String artifactFileName = artifactTemplateInfo.getFileName(); - - // check if artifacts already exist - for (ArtifactDefinition updatedArtifact : updatedArtifacts) { - if (updatedArtifact.getArtifactName().equals(artifactFileName)) { - if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) { - log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType())); - return resStatus; - } - resStatus = Either.left(updatedArtifact); - return resStatus; - } - - } - - Either, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils); - if (artifactContententStatus.isRight()) { - resStatus = Either.right(artifactContententStatus.right().value()); - return resStatus; - } - - Map json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), - oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts); - - Either, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), - shouldLock, inTransaction); - - if (uploadArtifactToService.isRight()) { - resStatus = Either.right(uploadArtifactToService.right().value()); - return resStatus; - } - ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value(); - updatedArtifacts.add(currentInfo); - - Either updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true); - if (updateEnvEither.isRight()) { - log.debug("failed to update parameters to artifact {}", artifactFileName); - resStatus = Either.right(updateEnvEither.right().value()); - return resStatus; - } - // TODO evg update env time ( must be separate US for this!!!!) - - updatedArtifacts.add(updateEnvEither.left().value()); - resStatus = Either.left(currentInfo); - - return resStatus; - - } - - private Either updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) { - Either resStatus = Either.left(currentInfo); - if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) { - - Either, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(), - componentsUtils); - if (artifactparamsStatus.isRight()) { - resStatus = Either.right(artifactparamsStatus.right().value()); - return resStatus; - } - Either, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false); - - if (propsStatus.isLeft()) { - List updatedHeatEnvParams = propsStatus.left().value(); - List currentHeatEnvParams = currentInfo.getListHeatParameters(); - // List newHeatEnvParams = new ArrayList(); - - if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) { - - String paramName; - for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) { - - paramName = heatEnvParam.getName(); - for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) { - if (paramName.equalsIgnoreCase(currHeatParam.getName())) { - - String updatedParamValue = heatEnvParam.getCurrentValue(); - if (updatedParamValue == null) - updatedParamValue = heatEnvParam.getDefaultValue(); - HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType()); - if (!paramType.getValidator().isValid(updatedParamValue, null)) { - ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE; - ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName); - resStatus = Either.right(responseFormat); - return resStatus; - } - currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null)); - // newHeatEnvParams.add(currHeatParam); - break; - } - } - } - currentInfo.setListHeatParameters(currentHeatEnvParams); - Either updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null); - if (updateArifactOnResource.isRight()) { - log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); - } - resStatus = Either.left(updateArifactOnResource.left().value()); - } - } - } - if (isUpdateEnv) { - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreArtifacts(false); - parametersView.setIgnoreGroups(false); - - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - resStatus = Either.right(responseFormat); - return resStatus; - - } - resource = eitherGerResource.left().value(); - Map artifacts = resource.getDeploymentArtifacts(); - Optional op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny(); - if (op.isPresent()) { - ArtifactDefinition artifactInfoHeatEnv = op.get(); - Either updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null); - if (updateArifactOnResource.isRight()) { - log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value()))); - } - resStatus = Either.left(updateArifactOnResource.left().value()); - } - } - return resStatus; - } - - private Either, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) { - // extract heat parameters - String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content); - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType); - if (heatParameters.isRight()) { - log.debug("File {} is not in expected key-value form in csar ", fileName); - BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName)); - - } - return Either.left(heatParameters.left().value()); - - } - - private Map buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) { - - Map json = new HashMap(); - String artifactName = artifactTemplateInfo.getFileName(); - - json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName()); - json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType()); - json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar"); - - // DE250204: There is no need to check if base64 encoding. - - // String encodedPayload = new String(artifactContentent); - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - String encodedPayload = Base64.encodeBase64String(artifactContentent); - // } - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - String displayName = artifactName; - if (artifactName.lastIndexOf(".") > 0) - displayName = artifactName.substring(0, artifactName.lastIndexOf(".")); - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); - List requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>() - : requiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - return json; - } - - private Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent, - List updatedRequiredArtifacts) { - - Map json = new HashMap(); - if (artifactId != null && !artifactId.isEmpty()) - json.put(Constants.ARTIFACT_ID, artifactId); - - json.put(Constants.ARTIFACT_NAME, artifactName); - json.put(Constants.ARTIFACT_TYPE, artifactType); - json.put(Constants.ARTIFACT_DESCRIPTION, description); - - String encodedPayload = new String(artifactContentent); - - // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent); - // if (!isEncoded) { - log.debug("payload is encoded. perform decode"); - encodedPayload = Base64.encodeBase64String(artifactContentent); - // } - - json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); - json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); - json.put(Constants.ARTIFACT_LABEL, label); - json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); - json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() - : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList())); - return json; - } - - @SuppressWarnings({ "unchecked", "static-access" }) - private Either>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) { - - try { - JsonObject jsonElement = new JsonObject(); - jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass()); - - JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE); - if (importStructureElement == null || importStructureElement.isJsonNull()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - Map>> artifactTemplateMap = new HashMap>>(); - artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class); - if (artifactTemplateMap.isEmpty()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - Set artifactsTypeKeys = artifactTemplateMap.keySet(); - Map> artifactsMap = new HashMap>(); - List allGroups = new ArrayList<>(); - for (String artifactsTypeKey : artifactsTypeKeys) { - - List> o = artifactTemplateMap.get(artifactsTypeKey); - Either, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o); - if (artifactTemplateInfoListPairStatus.isRight()) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(artifactTemplateInfoListPairStatus.right().value()); - } - List artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value(); - if (artifactTemplateInfoList == null) { - log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - - } - if(!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) - allGroups.addAll(artifactTemplateInfoList); - artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList); - } - int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups()); - Either validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter); - if (validateGroupNamesRes.isRight()) { - return Either.right(validateGroupNamesRes.right().value()); - } - return Either.left(artifactsMap); - } catch (Exception e) { - log.debug("Artifact file is not in expected format, fileName {}", artifactFileName); - log.debug("failed with exception.", e); - BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName)); - } - - } - - private Either, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List> jsonObject) { - List artifactTemplateInfoList = new ArrayList(); - for (Map o : jsonObject) { - Either artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null); - if (artifacttemplateInfoStatus.isRight()) { - return Either.right(artifacttemplateInfoStatus.right().value()); - } - - ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value(); - if (artifacttemplateInfo != null) { - artifactTemplateInfoList.add(artifacttemplateInfo); - } - - } - return Either.left(artifactTemplateInfoList); - } - - private Either createResourceInstancesRelations(User user, String yamlName, Resource resource, Map uploadResInstancesMap) { - log.debug("createResourceInstancesRelations try to create relations "); - List componentInstancesList = resource.getComponentInstances(); - if (uploadResInstancesMap == null) { - log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - if (componentInstancesList == null || componentInstancesList.isEmpty()) { - log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - log.debug("Before validateAndUpdatePropertyValue"); - Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName)); - - } - - Map> instProperties = new HashMap<>(); - Map>> instCapabilties = new HashMap<>(); - Map>> instRequirements = new HashMap<>(); - Map> instDeploymentArtifacts = new HashMap<>(); - Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); - Map originCompMap = new HashMap<>(); - List relations = new ArrayList<>(); - - Map> instInputs = new HashMap<>(); - - for (Entry entry : uploadResInstancesMap.entrySet()) { - log.trace("Processing entry: {}", entry); - UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); - ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - log.trace("Processing component instance: {}", compInstance); - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - Resource originResource; - if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { - Either getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid()); - if (getOriginResourceRes.isRight()) { - log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); - return Either.right(responseFormat); - } - originResource = getOriginResourceRes.left().value(); - originCompMap.put(originResource.getUniqueId(), originResource); - } else { - originResource = originCompMap.get(currentCompInstance.getComponentUid()); - } - if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) - instRequirements.put(currentCompInstance, originResource.getRequirements()); - if (MapUtils.isNotEmpty(originResource.getCapabilities())) { - Map> originCapabilities ; - if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { - originCapabilities = new HashMap<>(); - originResource.getCapabilities().entrySet().stream().forEach(e ->{ - List list = e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList()); - originCapabilities.put(e.getKey(), list); - }); - Map> newPropertiesMap = new HashMap<>(); - for(List capabilities : uploadComponentInstanceInfo.getCapabilities().values()){ - for(UploadCapInfo capability :capabilities){ - if(CollectionUtils.isNotEmpty(capability.getProperties())){ - newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p))); - } - } - } - for (List capabilities : originCapabilities.values()) { - List filteredCapabilities = capabilities.stream().filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList()); - for(CapabilityDefinition cap : filteredCapabilities){ - Either updateRes = updatePropertyValues(cap.getProperties(),newPropertiesMap.get(cap.getName()), allDataTypes.left().value()); - if(updateRes.isRight()){ - log.debug("Failed to update capability properties of capability {} . Status is {}. ", cap.getName(), updateRes.right().value()); - return Either.right(updateRes.right().value()); - } - } - } - } - else{ - originCapabilities = originResource.getCapabilities(); - } - instCapabilties.put(currentCompInstance, originCapabilities); - } - if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) - instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); - if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) - instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); - if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) - instAttributes.put(resourceInstanceId, originResource.getAttributes()); - if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { - ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value()); - if (addPropertiesValueToRiRes.getStatus() != 200) { - return Either.right(addPropertiesValueToRiRes); - } - } else { - ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value()); - if (addInputValueToRiRes.getStatus() != 200) { - return Either.right(addInputValueToRiRes); - } - } - } - - Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); - if (addPropToInst.isRight()) { - log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName); - return Either.right(responseFormat); - } - if (instInputs != null && !instInputs.isEmpty()) { - Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); - if (addInputToInst.isRight()) { - log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName); - return Either.right(responseFormat); - } - } - StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId()); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreComponentInstancesProperties(false); - parametersView.setIgnoreCapabilities(false); - parametersView.setIgnoreRequirements(false); - - Either eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - - return Either.right(responseFormat); - - } - - resource = eitherGetResource.left().value(); - - for (Entry entry : uploadResInstancesMap.entrySet()) { - UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); - ComponentInstance currentCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return Either.right(responseFormat); - } - - ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); - if (addRelationToRiRes.getStatus() != 200) { - return Either.right(addRelationToRiRes); - } - } - - addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); - if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { - log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); - return Either.right(responseFormat); - } - - if(resource.getResourceType() == ResourceTypeEnum.CVFC){ - eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(), uploadResInstancesMap); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - } - - log.debug("************* in create relations, getResource start"); - eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); - log.debug("************* in create relations, getResource end"); - if (eitherGetResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); - return Either.right(responseFormat); - } - return Either.left(eitherGetResource.left().value()); - } - - private Either updatePropertyValues(List properties, Map newProperties, Map allDataTypes) { - for(ComponentInstanceProperty property : properties){ - Either updateRes = updatePropertyValue(property ,newProperties.get(property.getName()), allDataTypes); - if(updateRes.isRight()){ - log.debug("Failed to update capability property {} . Status is {}. ", property.getName(), updateRes.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value()))); - } - } - return Either.left(true); - } - - private Either updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, Map allDataTypes) { - String value = null; - List getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - property.setValue(value); - return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes); - } - - private Either updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map uploadResInstancesMap) { - Either updateRes = null; - Map>> updatedInstCapabilities = new HashMap<>(); - Map>> updatedInstRequirements = new HashMap<>(); - StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId()); - if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){ - log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status); - updateRes = Either.right(status); - } - if(updateRes == null){ - fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements); - status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status); - updateRes = Either.right(status); - } - } - if(updateRes == null){ - updateRes = Either.left(resource); - } - return updateRes; - } - - - private void fillUpdatedInstCapabilitiesRequirements(List componentInstances, Map uploadResInstancesMap, - Map>> updatedInstCapabilities, Map>> updatedInstRequirements) { - - componentInstances.stream().forEach( i -> { - fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); - fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); - }); - } - - private void fillUpdatedInstRequirements(Map>> updatedInstRequirements, ComponentInstance instance, Map requirementsNamesToUpdate) { - Map> updatedRequirements = new HashMap<>(); - Set updatedReqNames = new HashSet<>(); - if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){ - for (Map.Entry> requirements : instance.getRequirements().entrySet()) { - updatedRequirements.put(requirements.getKey(), requirements.getValue().stream() - .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) - .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;}) - .collect(Collectors.toList())); - } - } - if(MapUtils.isNotEmpty(updatedRequirements)){ - updatedInstRequirements.put(instance, updatedRequirements); - } - } - - private void fillUpdatedInstCapabilities(Map>> updatedInstCapabilties, ComponentInstance instance, Map capabilitiesNamesToUpdate) { - Map> updatedCapabilities = new HashMap<>(); - Set updatedCapNames = new HashSet<>(); - if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){ - for (Map.Entry> requirements : instance.getCapabilities().entrySet()) { - updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream() - .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) - .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;}) - .collect(Collectors.toList())); - } - } - if(MapUtils.isNotEmpty(updatedCapabilities)){ - updatedInstCapabilties.put(instance, updatedCapabilities); - } - } - - private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List relations) { - List componentInstancesList = resource.getComponentInstances(); - - UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue; - - ComponentInstance currentCompInstance = null; - - for (ComponentInstance compInstance : componentInstancesList) { - - if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { - currentCompInstance = compInstance; - break; - } - - } - - if (currentCompInstance == null) { - log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - String resourceInstanceId = currentCompInstance.getUniqueId(); - - Map> regMap = uploadComponentInstanceInfo.getRequirements(); - - if (regMap != null) { - Iterator>> nodesRegValue = regMap.entrySet().iterator(); - - while (nodesRegValue.hasNext()) { - Entry> nodesRegInfoEntry = nodesRegValue.next(); - - List uploadRegInfoList = nodesRegInfoEntry.getValue(); - for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { - log.debug("Going to create relation {}", uploadRegInfo.getName()); - String regName = uploadRegInfo.getName(); - RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); - regCapRelDef.setFromNode(resourceInstanceId); - log.debug("try to find available requirement {} ", regName); - Either eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName()); - if (eitherReqStatus.isRight()) { - log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value()); - return eitherReqStatus.right().value(); - } - - RequirementDefinition validReq = eitherReqStatus.left().value(); - List reqAndRelationshipPairList = regCapRelDef.getRelationships(); - if (reqAndRelationshipPairList == null) - reqAndRelationshipPairList = new ArrayList<>(); - RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); - reqAndRelationshipPair.setRequirement(regName); - reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); - reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(validReq.getCapability()); - reqAndRelationshipPair.setRelationships(relationship); - - ComponentInstance currentCapCompInstance = null; - for (ComponentInstance compInstance : componentInstancesList) { - if (compInstance.getName().equals(uploadRegInfo.getNode())) { - currentCapCompInstance = compInstance; - break; - } - } - - if (currentCapCompInstance == null) { - log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); - log.debug("try to find aviable Capability req name is {} ", validReq.getName()); - CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo); - if (aviableCapForRel == null) { - log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId()); - BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(), - ErrorSeverity.ERROR); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); - return responseFormat; - } - reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); - reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); - reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(reqAndRelationshipPair); - reqAndRelationshipPairList.add(capReqRel); - regCapRelDef.setRelationships(reqAndRelationshipPairList); - relations.add(regCapRelDef); - } - } - } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); - return responseFormat; - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, - Map> instInputs, Map allDataTypes) { - Map> propMap = uploadComponentInstanceInfo.getProperties(); - if (propMap != null && propMap.size() > 0) { - Map currPropertiesMap = new HashMap(); - - List listFromMap = originResource.getInputs(); - if (listFromMap == null || listFromMap.isEmpty()) { - log.debug("failed to find properties "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - return responseFormat; - } - for (InputDefinition prop : listFromMap) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - List instPropList = new ArrayList<>(); - for (List propertyList : propMap.values()) { - - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - return responseFormat; - } - InputDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceInput property = null; - - String value = null; - List getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - String innerType = null; - property = new ComponentInstanceInput(curPropertyDef, value, null); - - Either validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); - } - - // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++); - // property.setUniqueId(uniqueId); - property.setValue(validatevalueEiter.left().value()); - - if (getInputs != null && !getInputs.isEmpty()) { - List getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId()); - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - - Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - } - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - // add rest of properties - if (!currPropertiesMap.isEmpty()) { - for (InputDefinition value : currPropertiesMap.values()) { - instPropList.add(new ComponentInstanceInput(value)); - } - } - instInputs.put(currentCompInstance.getUniqueId(), instPropList); - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, - Map> instProperties, Map allDataTypes) { - - Map> propMap = uploadComponentInstanceInfo.getProperties(); - Map currPropertiesMap = new HashMap(); - - List listFromMap = originResource.getProperties(); - if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { - log.debug("failed to find properties "); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); - return responseFormat; - } - if(listFromMap == null || listFromMap.isEmpty()){ - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - for (PropertyDefinition prop : listFromMap) { - String propName = prop.getName(); - if (!currPropertiesMap.containsKey(propName)) { - currPropertiesMap.put(propName, prop); - } - } - List instPropList = new ArrayList<>(); - if (propMap != null && propMap.size() > 0) { - for (List propertyList : propMap.values()) { - - UploadPropInfo propertyInfo = propertyList.get(0); - String propName = propertyInfo.getName(); - if (!currPropertiesMap.containsKey(propName)) { - log.debug("failed to find property {} ", propName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName); - return responseFormat; - } - PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); - ComponentInstanceProperty property = null; - - String value = null; - List getInputs = null; - boolean isValidate = true; - if (propertyInfo.getValue() != null) { - getInputs = propertyInfo.getGet_input(); - isValidate = getInputs == null || getInputs.isEmpty(); - if (isValidate) { - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType()); - } else - value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - String innerType = null; - property = new ComponentInstanceProperty(curPropertyDef, value, null); - - Either validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes); - if (validatevalueEiter.isRight()) { - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); - } - - property.setValue(validatevalueEiter.left().value()); - - if (getInputs != null && !getInputs.isEmpty()) { - List getInputValues = new ArrayList<>(); - for (GetInputValueDataDefinition getInput : getInputs) { - List inputs = resource.getInputs(); - if (inputs == null || inputs.isEmpty()) { - log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId()); - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - - Optional optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInput.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition input = optional.get(); - getInput.setInputId(input.getUniqueId()); - getInputValues.add(getInput); - - GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); - if (getInputIndex != null) { - optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny(); - if (!optional.isPresent()) { - log.debug("Failed to find input {} ", getInputIndex.getInputName()); - // @@TODO error message - return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - } - InputDefinition inputIndex = optional.get(); - getInputIndex.setInputId(inputIndex.getUniqueId()); - getInputValues.add(getInputIndex); - - } - - } - property.setGetInputValues(getInputValues); - } - instPropList.add(property); - // delete overriden property - currPropertiesMap.remove(property.getName()); - } - } - // add rest of properties - if (!currPropertiesMap.isEmpty()) { - for (PropertyDefinition value : currPropertiesMap.values()) { - instPropList.add(new ComponentInstanceProperty(value)); - } - } - instProperties.put(currentCompInstance.getUniqueId(), instPropList); - return componentsUtils.getResponseFormat(ActionStatus.OK); - } - - // US740820 Relate RIs according to capability name - private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get - // by - // capability - // type - return findAviableCapability(validReq, currentCapCompInstance); - } - return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); - } - - private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { - CapabilityDefinition cap = null; - Map> capMap = currentCapCompInstance.getCapabilities(); - if (!capMap.containsKey(validReq.getCapability())) { - return null; - } - Optional capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); - if (!capByName.isPresent()) { - return null; - } - cap = capByName.get(); - - if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = cap.getLeftOccurrences(); - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - - } - - } - return cap; - } - - private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) { - CapabilityDefinition aviableCapForRel = null; - Map> capMap = currentCapCompInstance.getCapabilities(); - if (capMap.containsKey(validReq.getCapability())) { - List capList = capMap.get(validReq.getCapability()); - - for (CapabilityDefinition cap : capList) { - if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = cap.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = cap.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - cap.setLeftOccurrences(String.valueOf(left)); - aviableCapForRel = cap; - break; - } else { - continue; - } - } else { - aviableCapForRel = cap; - break; - } - } - } - return aviableCapForRel; - } - - private Either findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) { - Map> comInstRegDefMap = currentCompInstance.getRequirements(); - List list = comInstRegDefMap.get(capName); - RequirementDefinition validRegDef = null; - if (list == null) { - for (Entry> entry : comInstRegDefMap.entrySet()) { - for (RequirementDefinition reqDef : entry.getValue()) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - - } - } - if (validRegDef != null) { - break; - } - } - } else { - for (RequirementDefinition reqDef : list) { - if (reqDef.getName().equals(regName)) { - if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - String leftOccurrences = reqDef.getLeftOccurrences(); - if (leftOccurrences == null) { - leftOccurrences = reqDef.getMaxOccurrences(); - } - int left = Integer.parseInt(leftOccurrences); - if (left > 0) { - --left; - reqDef.setLeftOccurrences(String.valueOf(left)); - validRegDef = reqDef; - break; - } else { - continue; - } - } else { - validRegDef = reqDef; - break; - } - } - } - } - if (validRegDef == null) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - return Either.left(validRegDef); - } - - @SuppressWarnings("unchecked") - public Either parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map createdNodesToscaResourceNames, Map nodeTypesInfo, String nodeName) { - - Map mappedToscaTemplate; - if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){ - mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); - } - else { - try { - //DE154502 Fail if duplicate key found in file - mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml); - - } catch(ParserException e) { - log.error("Failed to load yaml file {}", yamlFileName, e); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage()); - return Either.right(responseFormat); - } - } - Either toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - if (toscaElementEither.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - return Either.right(responseFormat); - } - - Either, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource); - if (createInputsEither.isRight()) { - ResponseFormat responseFormat = createInputsEither.right().value(); - return Either.right(responseFormat); - } - - Either, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames); - if (uploadResInstancesEither.isRight()) { - ResponseFormat responseFormat = uploadResInstancesEither.right().value(); - return Either.right(responseFormat); - } - - Either, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource); - if (createGroupsFromYaml.isRight()) { - ResponseFormat responseFormat = createGroupsFromYaml.right().value(); - return Either.right(responseFormat); - } - - ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo(); - parsedToscaYamlInfo.setInputs(createInputsEither.left().value()); - parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value()); - parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value()); - - return Either.left(parsedToscaYamlInfo); - } - - private Either createResourceInstances(User user, String yamlName, Resource resource, Map uploadResInstancesMap, boolean inTransaction, boolean needLock, - Map nodeNamespaceMap) { - - Either eitherResource = null; - log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); - if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - - return Either.right(responseFormat); - - } - Map existingnodeTypeMap = new HashMap<>(); - if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) { - nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue())); - } - - Iterator> nodesInfoValue = uploadResInstancesMap.entrySet().iterator(); - Map resourcesInstancesMap = new HashMap<>(); - while (nodesInfoValue.hasNext()) { - log.debug("*************Going to create resource instances {}", yamlName); - Entry uploadComponentInstanceInfoEntry = nodesInfoValue.next(); - UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); - - // updating type if the type is node type name - we need to take the - // updated name - log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); - } - - eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap); - if (eitherResource.isRight()) { - return eitherResource; - } - Resource refResource = eitherResource.left().value(); - - ComponentInstance componentInstance = new ComponentInstance(); - - componentInstance.setComponentUid(refResource.getUniqueId()); - - ComponentTypeEnum containerComponentType = resource.getComponentType(); - NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); - - if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils.isNotEmpty(refResource.getCapabilities())) { - setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - Either>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - if (getValidComponentInstanceCapabilitiesRes.isRight()) { - return Either.right(getValidComponentInstanceCapabilitiesRes.right().value()); - } else { - componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value()); - } - } - if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { - log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); - componentInstance.setName(uploadComponentInstanceInfo.getName()); - componentInstance.setIcon(origResource.getIcon()); - - resourcesInstancesMap.put(componentInstance, origResource); - - } - if (MapUtils.isNotEmpty(resourcesInstancesMap)) { - - StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false); - if (status != null && status != StorageOperationStatus.OK) { - log.debug("Failed to add component instances to container component {}", resource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)); - eitherResource = Either.right(responseFormat); - return eitherResource; - } - - } - - log.debug("*************Going to get resource {}", resource.getUniqueId()); - ComponentParametersView parametersView = new ComponentParametersView(); - parametersView.disableAll(); - parametersView.setIgnoreComponentInstances(false); - parametersView.setIgnoreUsers(false); - parametersView.setIgnoreInputs(false); // inputs are read when creating - // property values on instances - Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView); - log.debug("*************finished to get resource {}", resource.getUniqueId()); - if (eitherGerResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); - - return Either.right(responseFormat); - - } - - if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) { - - log.debug("Error when create resource inctanse from csar. ComponentInstances list empty"); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); - return Either.right(responseFormat); - - } - - return Either.left(eitherGerResource.left().value()); - } - - private void setCapabilityNamesTypes(Map> originCapabilities, Map> uploadedCapabilities) { - for(Entry> currEntry : uploadedCapabilities.entrySet()){ - if(originCapabilities.containsKey(currEntry.getKey())){ - currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); - } - } - for(Map.Entry> capabilities : originCapabilities.entrySet()){ - capabilities.getValue().stream().forEach(cap -> {if(uploadedCapabilities.containsKey(cap.getName())){uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {c.setName(cap.getName());c.setType(cap.getType());});};}); - } - - } - - private Either validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map nodeNamespaceMap) { - log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - Resource refResource = null; - if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { - refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); - } else { - Either findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); - if (findResourceEither.isRight()) { - log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); - return Either.right(responseFormat); - } - refResource = findResourceEither.left().value(); - nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); - } - String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); - if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState); - return Either.right(responseFormat); - } - - if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { - log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); - return Either.right(responseFormat); - } - return Either.left(refResource); - } - - private Either, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map toscaJson, Resource resource, Map createdNodesToscaResourceNames) { - Map moduleComponentInstances = new HashMap(); - Map substitutionMappings = null; - Either, ResponseFormat> result = Either.left(moduleComponentInstances); - Either, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES); - Either, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS); - if (eitherSubstitutionMappings.isLeft()) { - substitutionMappings = eitherSubstitutionMappings.left().value(); - } - if (eitherNodesTemlates.isLeft()) { - Map jsonNodeTemplates = eitherNodesTemlates.left().value(); - - Iterator> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry nodeNameValue = nodesNameValue.next(); - Either eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames); - if (eitherNode.isRight()) { - log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName()); - return Either.right(eitherNode.right().value()); - } else { - UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value(); - moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo); - } - - } - - } - if (moduleComponentInstances.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); - return Either.right(responseFormat); - } - - return result; - } - - @SuppressWarnings("unchecked") - private Either createModuleComponentInstanceInfo(Entry nodeTemplateJsonEntry, Map substitutionMappings, Map createdNodesToscaResourceNames) { - - UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo(); - Either result = Either.left(nodeTemplateInfo); - nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey()); - try { - if (nodeTemplateJsonEntry.getValue() instanceof String) { - String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue(); - nodeTemplateInfo.setType(nodeTemplateJsonString); - } else if (nodeTemplateJsonEntry.getValue() instanceof Map) { - Map nodeTemplateJsonMap = (Map) nodeTemplateJsonEntry.getValue(); - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) { - toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType); - } - nodeTemplateInfo.setType(toscaResourceType); - } - - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { - Either>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - nodeTemplateInfo.setRequirements(regResponse.left().value()); - } - } - - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { - Either>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap); - if (eitherCapRes.isRight()) - return Either.right(eitherCapRes.right().value()); - if (eitherCapRes.left().value().size() > 0) { - nodeTemplateInfo.setCapabilities(eitherCapRes.left().value()); - } - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - nodeTemplateInfo.setProperties(regResponse.left().value()); - } - } - if (substitutionMappings != null) { - if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { - Either, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); - if (getCapNamesToUpdateRes.isRight()) - return Either.right(getCapNamesToUpdateRes.right().value()); - if (getCapNamesToUpdateRes.left().value().size() > 0) { - nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value()); - } - } - if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { - Either, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); - if (getReqNamesToUpdateRes.isRight()) - return Either.right(getReqNamesToUpdateRes.right().value()); - if (getReqNamesToUpdateRes.left().value().size() > 0) { - nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value()); - } - } - } - } else { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); - log.debug("error when creating capability, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private Either, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map> elements) { - Either, ResponseFormat> response; - try { - Map namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey())); - response = Either.left(namesToUpdate); - } catch (Exception e) { - log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName()); - response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return response; - } - - @SuppressWarnings("unchecked") - private Either>, ResponseFormat> createPropModuleFromYaml(Map nodeTemplateJsonMap) { - Map> moduleProp = new HashMap>(); - Either>, ResponseFormat> response = Either.left(moduleProp); - Either, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES); - if (toscaProperties.isLeft()) { - Map jsonProperties = toscaProperties.left().value(); - for (Entry jsonPropObj : jsonProperties.entrySet()) { - // Property - String propName = jsonPropObj.getKey(); - Object propValue = jsonPropObj.getValue(); - - if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - if (valueContainsPattern(TOKEN_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - if (valueContainsPattern(CONCAT_PATTERN, propValue)) { - log.trace("Ignore property value {}.", propName); - continue; - } - - UploadPropInfo propertyDef = new UploadPropInfo(); - propertyDef.setValue(propValue); - propertyDef.setName(propName); - if (propValue instanceof Map) { - if (((Map) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - propertyDef.setType(((Map) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString()); - } - - if (((Map) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()) - || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - createGetInputModuleFromMap(propName, (Map) propValue, propertyDef); - } - - if (((Map) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - propertyDef.setDescription(((Map) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString()); - } - if (((Map) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) { - propertyDef.setValue(((Map) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())); - } - if (((Map) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) { - propertyDef.setPassword(Boolean.getBoolean(((Map) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString())); - } else { - propertyDef.setValue(propValue); - } - } else if (propValue instanceof List) { - List propValueList = (List) propValue; - - createInputPropList(propertyDef, propValueList); - propertyDef.setValue(propValue); - } - - if (moduleProp.containsKey(propName)) { - moduleProp.get(propName).add(propertyDef); - } else { - List list = new ArrayList(); - list.add(propertyDef); - moduleProp.put(propName, list); - } - } - } - return response; - } - - @SuppressWarnings("unchecked") - private void createInputPropList(UploadPropInfo propertyDef, List propValueList) { - for (Object objValue : propValueList) { - - if (objValue instanceof Map) { - Map objMap = (Map) objValue; - if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) - createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef); - else { - Set keys = objMap.keySet(); - for (String key : keys) { - Object value = objMap.get(key); - if (value instanceof Map) { - createGetInputModuleFromMap(key, (Map) value, propertyDef); - - } else if (value instanceof List) { - List propSubValueList = (List) value; - - createInputPropList(propertyDef, propSubValueList); - } - - } - } - - } else if (objValue instanceof List) { - List propSubValueList = (List) objValue; - - createInputPropList(propertyDef, propSubValueList); - - } - - } - } - - @SuppressWarnings("unchecked") - private void createGetInputModuleFromMap(String propName, Map propValue, UploadPropInfo propertyDef) { - - if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); - List getInputs = propertyDef.getGet_input(); - if (getInputs == null) { - getInputs = new ArrayList(); - } - if (getInput instanceof String) { - - getInputInfo.setInputName((String) getInput); - getInputInfo.setPropName(propName); - - } else if (getInput instanceof List) { - List getInputList = (List) getInput; - getInputInfo.setPropName(propName); - getInputInfo.setInputName((String) getInputList.get(0)); - if (getInputList.size() > 1) { - Object indexObj = getInputList.get(1); - if (indexObj instanceof Integer) { - getInputInfo.setIndexValue((Integer) indexObj); - } else if (indexObj instanceof Float) { - int index = ((Float) indexObj).intValue(); - getInputInfo.setIndexValue(index); - } else if (indexObj instanceof Map && ((Map) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { - Object index = ((Map) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName()); - GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); - getInputInfoIndex.setInputName((String) index); - getInputInfoIndex.setPropName(propName); - getInputInfo.setGetInputIndex(getInputInfoIndex); - } - getInputInfo.setList(true); - } - - } - getInputs.add(getInputInfo); - propertyDef.setGet_input(getInputs); - propertyDef.setValue(propValue); - } else { - Set keys = propValue.keySet(); - for (String key : keys) { - Object value = propValue.get(key); - if (value instanceof Map) { - createGetInputModuleFromMap(key, (Map) value, propertyDef); - - } else if (value instanceof List) { - List valueList = (List) value; - for (Object o : valueList) { - if (o instanceof Map) { - createGetInputModuleFromMap(key, (Map) o, propertyDef); - - } - } - - } - - } - - } - } - - /* - * private boolean valueContainsStrReplace(Object propValue) { - * - * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher = - * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); } - * - * return result; } - * - * private boolean valueContainsToken(Object propValue) { - * - * log.debug("valueContainsToken value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsToken value is {}", propValue.getClass()); Matcher matcher = TOKEN_PATTERN.matcher(propValue.toString()); result = - * matcher.find(); } - * - * return result; } - */ - - private boolean valueContainsPattern(Pattern pattern, Object propValue) { - - log.debug("valueContainsToken value is {}", propValue); - boolean result = false; - if (propValue != null) { - log.trace("valueContainspattern value is {}", propValue.getClass()); - Matcher matcher = pattern.matcher(propValue.toString()); - result = matcher.find(); - } - - return result; - - } - @SuppressWarnings("unchecked") - private Either>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { - Map> moduleRequirements = new HashMap>(); - Either>, ResponseFormat> response = Either.left(moduleRequirements); - Either, ResultStatusEnum> requirementsListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); - - if (requirementsListRes.isLeft()) { - for (Object jsonReqObj : requirementsListRes.left().value()) { - String reqName = ((Map) jsonReqObj).keySet().iterator().next(); - Object reqJson = ((Map) jsonReqObj).get(reqName); - Either eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } else { - Either, ResultStatusEnum> requirementsMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); - if (requirementsMapRes.isLeft()) { - for (Map.Entry entry: requirementsMapRes.left().value().entrySet()) { - String reqName = entry.getKey(); - Object reqJson = entry.getValue(); - Either eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } - } - return response; - } - - private Either addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,Map> moduleRequirements, Object requirementJson, String requirementName) { - - Either eitherRequirement = createModuleNodeTemplateReg(requirementJson); - if (eitherRequirement.isRight()) { - log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo); - return Either.right(eitherRequirement.right().value()); - } else { - UploadReqInfo requirementDef = eitherRequirement.left().value(); - requirementDef.setName(requirementName); - if (moduleRequirements.containsKey(requirementName)) { - moduleRequirements.get(requirementName).add(requirementDef); - } else { - List list = new ArrayList(); - list.add(requirementDef); - moduleRequirements.put(requirementName, list); - } - } - return Either.left(eitherRequirement.left().value()); - } - - @SuppressWarnings("unchecked") - private Either>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { - Map> moduleCap = new HashMap<>(); - Either>, ResponseFormat> response = Either.left(moduleCap); - Either, ResultStatusEnum> capabilitiesListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); - if (capabilitiesListRes.isLeft()) { - for (Object jsonCapObj : capabilitiesListRes.left().value()) { - String key = ((Map) jsonCapObj).keySet().iterator().next(); - Object capJson = ((Map) jsonCapObj).get(key); - Either eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, key); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } else { - Either, ResultStatusEnum> capabilitiesMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); - if (capabilitiesMapRes.isLeft()) { - for (Map.Entry entry: capabilitiesMapRes.left().value().entrySet()) { - String capName = entry.getKey(); - Object capJson = entry.getValue(); - Either eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, capName); - if (eitherCap.isRight()) { - return Either.right(eitherCap.right().value()); - } - } - } - } - return response; - } - - private Either addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, Map> moduleCap, Object capJson, String key) { - - Either eitherCap = createModuleNodeTemplateCap(capJson); - if (eitherCap.isRight()) { - log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo); - return Either.right(eitherCap.right().value()); - } else { - UploadCapInfo capabilityDef = eitherCap.left().value(); - capabilityDef.setKey(key); - if (moduleCap.containsKey(key)) { - moduleCap.get(key).add(capabilityDef); - } else { - List list = new ArrayList(); - list.add(capabilityDef); - moduleCap.put(key, list); - } - } - return Either.left( eitherCap.left().value()); - } - - @SuppressWarnings("unchecked") - private Either createModuleNodeTemplateCap(Object capObject) { - UploadCapInfo capTemplateInfo = new UploadCapInfo(); - Either result = Either.left(capTemplateInfo); - - if (capObject instanceof String) { - String nodeTemplateJsonString = (String) capObject; - capTemplateInfo.setNode(nodeTemplateJsonString); - } else if (capObject instanceof Map) { - Map nodeTemplateJsonMap = (Map) capObject; - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - Either, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES); - if (validSourceTypesRes.isLeft()) { - capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList())); - } - } - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (!regResponse.left().value().isEmpty()) { - List properties = new ArrayList(); - regResponse.left().value().values().forEach(list -> properties.addAll(list)); - if (!properties.isEmpty()) - capTemplateInfo.setProperties(properties); - } - } - } - return result; - } - - @SuppressWarnings("unchecked") - private Either createModuleNodeTemplateReg(Object regObject) { - - UploadReqInfo regTemplateInfo = new UploadReqInfo(); - Either result = Either.left(regTemplateInfo); - - if (regObject instanceof String) { - String nodeTemplateJsonString = (String) regObject; - regTemplateInfo.setNode(nodeTemplateJsonString); - } else if (regObject instanceof Map) { - Map nodeTemplateJsonMap = (Map) regObject; - // Type - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - // US740820 Relate RIs according to capability name - if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { - regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); - } - } - return result; - } - - public Either propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) { - - Either result = null; - try { - if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){ - result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - if(result.isRight()){ - return result; - } - resource = result.left().value(); - } - if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { - Either, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock); - result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value()); - return result; - } - return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); - } catch (Exception e) { - log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - - private Either nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - Either result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock); - if (result.isLeft()) { - result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock); - } - if (result.isLeft()) { - result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock); - } - return result; - } - - private Either nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); - } - - /* - * /** - * - * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead - */ - /* - * public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return - * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); } - */ - - public Either, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, String nodeName, boolean isNested) { - - // check if resource already exist - Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); - Either, ResponseFormat> result = null; - - // create - if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - - Either latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName()); - if (csarInfo!= null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ - latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight()); - // update - if (latestByToscaName.isLeft()) { - log.debug("validate derived before update"); - Either eitherValidation = validateNestedDerivedFromDuringUpdate(latestByToscaName.left().value(), resource, ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion())); - if (eitherValidation.isRight()) { - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } else { - result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, isNormative, needLock, isNested); - } - } - } - if (result == null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){ - result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); - } else if (result == null){ - StorageOperationStatus status = latestByName.right().value(); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - log.debug("resource already exist {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - } - - } - - // update - else if (latestByName.isLeft()) { - result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, isNested); - } - - // error - else { - StorageOperationStatus status = latestByName.right().value(); - log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource); - componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - } - return result; - - } - - private Either, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { - log.debug("resource with name {} does not exist. create new resource", resource.getName()); - Either response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); - if (response.isRight()) { - return Either.right(response.right().value()); - } - Either createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null); - if (createResponse.isRight()) { - return Either.right(createResponse.right().value()); - } else { - ImmutablePair resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED); - ASDCKpiApi.countImportResourcesKPI(); - return Either.left(resourcePair); - - } - } - - public boolean isResourceExist(String resourceName) { - Either latestByName = toscaOperationFacade.getLatestByName(resourceName); - return latestByName.isLeft(); - } - - private Either, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) { - String lockedResourceId = oldResource.getUniqueId(); - log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState()); - Either, ResponseFormat> result = null; - try { - if (needLock) { - Either lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - } - - Either prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false); - if (prepareResourceForUpdate.isRight()) { - ResponseFormat responseFormat = prepareResourceForUpdate.right().value(); - log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage()); - componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(prepareResourceForUpdate.right().value()); - return result; - } - oldResource = prepareResourceForUpdate.left().value(); - - mergeOldResourceMetadataWithNew(oldResource, newResource); - - Either validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - if (validateFieldsResponse.isRight()) { - result = Either.right(validateFieldsResponse.right().value()); - return result; - } - - validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); - if (validateFieldsResponse.isRight()) { - return Either.right(validateFieldsResponse.right().value()); - } - - // contact info normalization - newResource.setContactId(newResource.getContactId().toLowerCase()); - // non-updatable fields - newResource.setCreatorUserId(user.getUserId()); - newResource.setCreatorFullName(user.getFullName()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setLastUpdaterFullName(user.getFullName()); - newResource.setUniqueId(oldResource.getUniqueId()); - newResource.setVersion(oldResource.getVersion()); - newResource.setInvariantUUID(oldResource.getInvariantUUID()); - newResource.setLifecycleState(oldResource.getLifecycleState()); - newResource.setUUID(oldResource.getUUID()); - newResource.setNormalizedName(oldResource.getNormalizedName()); - newResource.setSystemName(oldResource.getSystemName()); - if (oldResource.getCsarUUID() != null) { - newResource.setCsarUUID(oldResource.getCsarUUID()); - } - if (oldResource.getImportedToscaChecksum() != null) { - newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); - } - newResource.setAbstract(oldResource.isAbstract()); - - if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) { - newResource.setDerivedFrom(oldResource.getDerivedFrom()); - } - // TODO rhalili: handle artifacts here (delete from old resource and - // add for new) - // TODO rbetzer: remove after migration - in case of resources - // created without tosca artifacts - add the placeholders - if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { - setToscaArtifactsPlaceHolders(newResource, user); - } - Either overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource); - - if (overrideResource.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); - componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - result = Either.right(responseFormat); - return result; - } - - log.debug("Resource updated successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null); - - ImmutablePair resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK); - result = Either.left(resourcePair); - return result; - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } else if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - if (needLock == true) { - log.debug("unlock resource {}", lockedResourceId); - graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); - } - } - - } - - /** - * Merge old resource with new. Keep old category and vendor name without change - * - * @param oldResource - * @param newResource - */ - private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { - - // keep old category and vendor name without change - // merge the rest of the resource metadata - if (newResource.getTags() == null || newResource.getTags().isEmpty()) { - newResource.setTags(oldResource.getTags()); - } - - if (newResource.getDescription() == null) { - newResource.setDescription(oldResource.getDescription()); - } - - if (newResource.getVendorRelease() == null) { - newResource.setVendorRelease(oldResource.getVendorRelease()); - } - - if (newResource.getResourceVendorModelNumber() == null) { - newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); - } - - if (newResource.getContactId() == null) { - newResource.setContactId(oldResource.getContactId()); - } - - newResource.setCategories(oldResource.getCategories()); - newResource.setVendorName(oldResource.getVendorName()); - } - - private Either prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) { - - Either result = Either.left(latestResource); - // check if user can edit resource - if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) { - // checkout - Either changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock); - result = changeState; - } - - return result; - } - - public Either validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { - - Either eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - eitherValidation = validateResourceType(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setContactId(resource.getContactId().toLowerCase()); - if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { - String resourceSystemName; - if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){ - resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); - } else { - resourceSystemName = resource.getSystemName(); - } - resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); - } - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - // TODO - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - resource.setInvariantUUID(invariantUUID); - - return Either.left(resource); - } - - private Either validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) { - Either eitherResult = Either.left(true); - if (resource.getResourceType() == null) { - log.debug("Invalid resource type for resource"); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - return eitherResult; - } - - private Either validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) { - Either eitherResult = Either.left(true); - if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { - log.debug("validate interface lifecycle Types Exist"); - Iterator intItr = resource.getInterfaces().values().iterator(); - while (intItr.hasNext() && eitherResult.isLeft()) { - InterfaceDefinition interfaceDefinition = intItr.next(); - String intType = interfaceDefinition.getUniqueId(); - Either eitherCapTypeFound = interfaceTypeOperation.getInterface(intType); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType); - log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); - log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name()); - } - - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - - } - } - return eitherResult; - } - - private Either validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - - Either eitherResult = Either.left(true); - if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { - log.debug("validate capability Types Exist - capabilities section"); - - for (Entry> typeEntry : resource.getCapabilities().entrySet()) { - - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } - - if (resource.getRequirements() != null && resource.getRequirements().size() > 0) { - log.debug("validate capability Types Exist - requirements section"); - for (String type : resource.getRequirements().keySet()) { - eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction); - if (eitherResult.isRight()) { - return Either.right(eitherResult.right().value()); - } - } - } - - return eitherResult; - } - - // @param typeObject- the object to which the validation is done - private Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, AuditingActionEnum actionEnum, Either eitherResult, String type, - boolean inTransaction) { - Either eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); - } - log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = null; - if (type != null) - errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); - else - errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - return eitherResult; - } - - private Either validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either eitherResult, - Entry> typeEntry, boolean inTransaction) { - Either eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction); - if (eitherCapTypeFound.isRight()) { - if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey()); - log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName()); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); - } - log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey()); - eitherResult = Either.right(errorResponse); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - } - CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); - if (capabilityTypeDefinition.getProperties() != null) { - for (CapabilityDefinition capDef : typeEntry.getValue()) { - List properties = capDef.getProperties(); - if (properties == null || properties.isEmpty()) { - properties = new ArrayList(); - for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); - properties.add(newProp); - } - } else { - for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { - PropertyDefinition porpFromDef = prop.getValue(); - List propsToAdd = new ArrayList<>(); - for (ComponentInstanceProperty cip : properties) { - if (!cip.getName().equals(porpFromDef.getName())) { - ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); - propsToAdd.add(newProp); - } - } - if (!propsToAdd.isEmpty()) { - properties.addAll(propsToAdd); - } - } - } - capDef.setProperties(properties); - } - } - return eitherResult; - } - - public Either createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap additionalParams) { - // create resource - - // lock new resource name in order to avoid creation resource with same - // name - if (inTransaction == false) { - Either lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams); - return Either.right(responseFormat); - } - - log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); - } - try { - if (resource.deriveFromGeneric()) { - Either genericResourceEither = handleResourceGenericType(resource); - if (genericResourceEither.isRight()) - return genericResourceEither; - } - - Either respStatus = createResourceTransaction(resource, user, isNormative, inTransaction); - if (respStatus.isLeft()) { - auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams); - ASDCKpiApi.countCreatedResourcesKPI(); - } else - componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams); - return respStatus; - - } finally { - if (inTransaction == false) { - graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - } - - private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap additionalParams) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams); - } - - private Either createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) { - // validate resource name uniqueness - log.debug("validate resource name"); - Either eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (eitherValidation.isRight()) { - log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); - return Either.right(errorResponse); - } - if (eitherValidation.left().value()) { - log.debug("resource with name: {}, already exists", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - return Either.right(errorResponse); - } - - log.debug("send resource {} to dao for create", resource.getName()); - - createArtifactsPlaceHolderData(resource, user); - - // - - // enrich object - if (!isNormative) { - log.debug("enrich resource with creator, version and state"); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setVersion(INITIAL_VERSION); - resource.setHighestVersion(true); - if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) - resource.setAbstract(false); - } - - Either createToscaElement = toscaOperationFacade.createToscaComponent(resource); - if (createToscaElement.isLeft()) { - return Either.left(createToscaElement.left().value()); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource); - - return Either.right(responseFormat); - } - - private void createArtifactsPlaceHolderData(Resource resource, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String resourceUniqueId = - // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(), - // resource.getResourceVersion()); - - setInformationalArtifactsPlaceHolder(resource, user); - setDeploymentArtifactsPlaceHolder(resource, user); - setToscaArtifactsPlaceHolders(resource, user); - } - - @SuppressWarnings("unchecked") - @Override - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - Resource resource = (Resource) component; - Map artifactMap = resource.getDeploymentArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap(); - } - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts(); - if (deploymentResourceArtifacts != null) { - Iterator> iterator = deploymentResourceArtifacts.entrySet().iterator(); - while (iterator.hasNext()) { - Entry currEntry = iterator.next(); - boolean shouldCreateArtifact = true; - Map artifactDetails = (Map) currEntry.getValue(); - Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); - if (object != null) { - List artifactTypes = (List) object; - if (!artifactTypes.contains(resource.getResourceType().name())) { - shouldCreateArtifact = false; - continue; - } - } else { - log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey()); - } - if (shouldCreateArtifact) { - if (artifactsBusinessLogic != null) { - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT); - if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - } - } - } - resource.setDeploymentArtifacts(artifactMap); - } - - @SuppressWarnings("unchecked") - private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { - Map artifactMap = resource.getArtifacts(); - if (artifactMap == null) { - artifactMap = new HashMap(); - } - String resourceUniqueId = resource.getUniqueId(); - List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory(); - List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType(); - Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts(); - List categories = resource.getCategories(); - boolean isCreateArtifact = true; - if (exludeResourceCategory != null) { - String category = categories.get(0).getName(); - for (String exlude : exludeResourceCategory) { - if (exlude.equalsIgnoreCase(category)) { - isCreateArtifact = false; - break; - } - } - - } - if (isCreateArtifact && exludeResourceType != null) { - String resourceType = resource.getResourceType().name(); - for (String type : exludeResourceType) { - if (type.equalsIgnoreCase(resourceType)) { - isCreateArtifact = false; - break; - } - } - - } - - if (informationalResourceArtifacts != null && isCreateArtifact) { - Set keys = informationalResourceArtifacts.keySet(); - for (String informationalResourceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalResourceArtifacts.get(informationalResourceArtifactName); - ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - } - } - resource.setArtifacts(artifactMap); - } - - /** - * deleteResource - * - * @param resourceId - * @param user - * @return - */ - public ResponseFormat deleteResource(String resourceId, User user) { - ResponseFormat responseFormat; - Either eitherCreator = validateUserExists(user, "Delete Resource", false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - - Either resourceStatus = toscaOperationFacade.getToscaElement(resourceId); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {}", resourceId); - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); - } - - Resource resource = resourceStatus.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either lockResult = lockComponent(resourceId, resource, "Mark resource to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - - result = markComponentToDelete(resource); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); - } - - } - - public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - Either eitherCreator = validateUserExists(user, "Delete Resource", false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - - // Resource resource = null; - Resource resource = null; - StorageOperationStatus result = StorageOperationStatus.OK; - try { - - Either resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); - if (resourceStatus.isRight()) { - log.debug("failed to get resource {} version {}", resourceName, version); - return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); - } - - resource = resourceStatus.left().value(); - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - if (resource != null) { - Either lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - try { - result = markComponentToDelete(resource); - if (!result.equals(StorageOperationStatus.OK)) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); - return responseFormat; - } - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); - } - } - return responseFormat; - } - - public Either getResource(String resourceId, User user) { - - if (user != null) { - Either eitherCreator = validateUserExists(user, "Create Resource", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - } - - // IResourceOperation dataModel = getResourceOperation(); - Either storageStatus = toscaOperationFacade.getToscaElement(resourceId); - if (storageStatus.isRight()) { - log.debug("failed to get resource by id {}", resourceId); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId)); - } - if(!(storageStatus.left().value() instanceof Resource)){ - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); - } - return Either.left(storageStatus.left().value()); - - } - - public Either getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) { - - Either resp = validateUserExists(userId, "get Resource By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); - if (getResource.isRight()) { - log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); - } - return Either.left(getResource.left().value()); - } - - /** - * updateResourceMetadata - * - * @param user - modifier data (userId) - * @param inTransaction TODO - * @param resourceIdToUpdate - the resource identifier - * @param newResource - * @return Either - */ - public Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) { - - Either resp = validateUserExists(user.getUserId(), "update Resource Metadata", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - // IResourceOperation dataModel = getResourceOperation(); - log.debug("Get resource with id {}", resourceIdToUpdate); - boolean needToUnlock = false; - boolean rollbackNeeded = true; - - try { - // Either storageStatus = - // dataModel.getResource_tx(resourceIdToUpdate, false); - if (currentResource == null) { - Either storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate); - if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); - } - - currentResource = storageStatus.left().value(); - } - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - // lock resource - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate); - log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); - return Either.right(responseFormat); - } - - needToUnlock = true; - - // critical section starts here - // convert json to object - - // Update and updated resource must have a non-empty "derivedFrom" - // list - // This code is not called from import resources, because of root - // VF "derivedFrom" should be null (or ignored) - if (ModelConverter.isAtomicComponent(currentResource)) { - Either derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null); - if (derivedFromNotEmptyEither.isRight()) { - log.debug("for updated resource {}, derived from field is empty", newResource.getName()); - return Either.right(derivedFromNotEmptyEither.right().value()); - } - - derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null); - if (derivedFromNotEmptyEither.isRight()) { - log.debug("for current resource {}, derived from field is empty", currentResource.getName()); - return Either.right(derivedFromNotEmptyEither.right().value()); - } - } else { - newResource.setDerivedFrom(null); - } - - Either dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true); - if (dataModelResponse.isRight()) { - log.debug("failed to update resource metadata!!!"); - rollbackNeeded = true; - return Either.right(dataModelResponse.right().value()); - } - - log.debug("Resource metadata updated successfully!!!"); - rollbackNeeded = false; - return Either.left(dataModelResponse.left().value()); - - } finally { - if (!inTransaction) { - if (rollbackNeeded) { - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - - if (needToUnlock) { - graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); - } - } - } - - private Either,Boolean> updateComponentGroupName(String replacePattern , String with ,List oldGroup){ - if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){ - if (log.isInfoEnabled()) - log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" ); - return Either.right(false); - } - List list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList()); - for ( GroupDefinition group : list) { - if ( group!=null && group.isSamePrefix( replacePattern ) ){ - String prefix = group.getName().substring( 0, replacePattern.length() ); - String newGroupName = group.getName().replaceFirst(prefix , with); - group.setName(newGroupName); - //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id - //group.setUniqueId(newUid); - } - } - return Either.left(list); - } - - private boolean isComponentNameChanged(Resource newResource,Resource oldResource){ - if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional - String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - return !oldName.equals(futureName); - } - return false; - } - - private Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { - //region -> Update groups name for newResource - if ( isComponentNameChanged( currentResource , newResource) ){ - String replacePattern = Optional.ofNullable( //get currentResource name from metadata - Optional.ofNullable( Optional.ofNullable( currentResource ) - .orElse(null).getComponentMetadataDefinition() ) - .orElse(null).getMetadataDataDefinition() ) - .orElse(null).getName(); - String with = Optional.ofNullable( //get newResource name from metadata - Optional.ofNullable( Optional.ofNullable( newResource ) - .orElse(null).getComponentMetadataDefinition() ) - .orElse(null).getMetadataDataDefinition() ) - .orElse(null).getName(); - if ( with != null && replacePattern != null ){ - Either,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups()); - if (result.isLeft()) - newResource.setGroups( (List)result.left().value() ); - } - } - //endregion - - Either validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false); - if (validateResourceFields.isRight()) { - return Either.right(validateResourceFields.right().value()); - } - // Setting last updater and uniqueId - newResource.setContactId(newResource.getContactId().toLowerCase()); - newResource.setLastUpdaterUserId(user.getUserId()); - newResource.setUniqueId(resourceIdToUpdate); - // Cannot set highest version through UI - newResource.setHighestVersion(currentResource.isHighestVersion()); - newResource.setCreationDate(currentResource.getCreationDate()); - - Either processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction); - - if (processUpdateOfDerivedFrom.isRight()) { - log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); - return Either.right(processUpdateOfDerivedFrom.right().value()); - } - - log.debug("send resource {} to dao for update", newResource.getUniqueId()); - if (newResource!=null && newResource.getGroups()!=null){ - for ( GroupDefinition group : newResource.getGroups() ){ - if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null) - groupBusinessLogic.validateAndUpdateGroupMetadata( - newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() , - user, - ComponentTypeEnum.RESOURCE_INSTANCE, - group, - true , - false) ; - } - } - Either dataModelResponse = toscaOperationFacade.updateToscaElement(newResource); - - if (dataModelResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); - return Either.right(responseFormat); - } else if (dataModelResponse.left().value() == null) { - log.debug("No response from updateResource"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left(dataModelResponse.left().value()); - } - - /** - * validateResourceFieldsBeforeCreate - * - * @param user - modifier data (userId) - * @param dataModel - IResourceOperation for resource crud - * @param resource - Resource object to validate - * @return Either - */ - private Either validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - Either componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum); - if (componentsFieldsValidation.isRight()) { - return componentsFieldsValidation; - } - - // validate name - - /* - * log.debug("validate resource name"); Either eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - * - * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate icon - /* - * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate tags - /* - * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate category - log.debug("validate category"); - Either eitherValidation = validateCategory(user, resource, actionEnum, inTransaction); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate vendor name & release & model number - log.debug("validate vendor name"); - eitherValidation = validateVendorName(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate vendor release"); - eitherValidation = validateVendorReleaseName(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate resource vendor model number"); - eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate contact info - /* - * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; } - */ - - // validate cost - log.debug("validate cost"); - eitherValidation = validateCost(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate licenseType - log.debug("validate licenseType"); - eitherValidation = validateLicenseType(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate template (derived from) - log.debug("validate derived from"); - if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { - resource.setDerivedFrom(null); - } - eitherValidation = validateDerivedFromExist(user, resource, actionEnum); - if (eitherValidation.isRight()) { - return Either.right(eitherValidation.right().value()); - } - - // warn about non-updatable fields - checkComponentFieldsForOverrideAttempt(resource); - String currentCreatorFullName = resource.getCreatorFullName(); - if (currentCreatorFullName != null) { - log.warn("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); - if (currentLastUpdaterFullName != null) { - log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = resource.getLastUpdateDate(); - if (currentLastUpdateDate != null) { - log.warn("Resource last update date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = resource.isAbstract(); - if (currentAbstract != null) { - log.warn("Resource abstract is automatically set and cannot be updated"); - } - - return Either.left(true); - } - - /** - * validateResourceFieldsBeforeUpdate - * - * @param currentResource - Resource object to validate - * @param isNested - * @return Either - */ - private Either validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); - - // validate resource name - log.debug("validate resource name before update"); - Either eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // validate description - log.debug("validate description before update"); - eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate icon before update"); - eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate tags before update"); - eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate vendor name before update"); - eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate resource vendor model number before update"); - eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - - log.debug("validate vendor release before update"); - eitherValidation = validateVendorReleaseName(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate contact info before update"); - eitherValidation = validateContactId(null, updateInfoResource, null); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate derived before update"); - eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - log.debug("validate category before update"); - eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); - if (eitherValidation.isRight()) { - return eitherValidation; - } - - // warn about non-updatable fields - String currentResourceVersion = currentResource.getVersion(); - String updatedResourceVersion = updateInfoResource.getVersion(); - - if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { - log.warn("Resource version is automatically set and cannot be updated"); - } - - String currentCreatorUserId = currentResource.getCreatorUserId(); - String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); - - if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { - log.warn("Resource Creator UserId is automatically set and cannot be updated"); - } - - String currentCreatorFullName = currentResource.getCreatorFullName(); - String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); - - if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { - log.warn("Resource Creator fullname is automatically set and cannot be updated"); - } - - String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); - String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); - - if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { - log.warn("Resource LastUpdater userId is automatically set and cannot be updated"); - } - - String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); - String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); - - if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { - log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); - } - - Long currentCreationDate = currentResource.getCreationDate(); - Long updatedCreationDate = updateInfoResource.getCreationDate(); - - if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { - log.warn("Resource Creation date is automatically set and cannot be updated"); - } - - Long currentLastUpdateDate = currentResource.getLastUpdateDate(); - Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); - - if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { - log.warn("Resource last update date is automatically set and cannot be updated"); - } - - LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); - LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); - - if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { - log.warn("Resource lifecycle state date is automatically set and cannot be updated"); - } - - Boolean currentAbstract = currentResource.isAbstract(); - Boolean updatedAbstract = updateInfoResource.isAbstract(); - - if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { - log.warn("Resource abstract is automatically set and cannot be updated"); - } - - Boolean currentHighestVersion = currentResource.isHighestVersion(); - Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); - - if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { - log.warn("Resource highest version is automatically set and cannot be updated"); - } - - String currentUuid = currentResource.getUUID(); - String updatedUuid = updateInfoResource.getUUID(); - - if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { - log.warn("Resource UUID is automatically set and cannot be updated"); - } - - ResourceTypeEnum currentResourceType = currentResource.getResourceType(); - ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType(); - - if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) { - log.warn("Resource Type cannot be updated"); - - } - updateInfoResource.setResourceType(currentResource.getResourceType()); - - String currentInvariantUuid = currentResource.getInvariantUUID(); - String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Resource invariant UUID is automatically set and cannot be updated"); - updateInfoResource.setInvariantUUID(currentInvariantUuid); - } - return Either.left(true); - } - - /* - * private Either validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName(); - * - * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } - * - * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); - * } - * - * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, - * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName( - * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ; - * - * return Either.left(true); } - */ - - private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { - String resourceNameUpdated = updateInfoResource.getName(); - String resourceNameCurrent = currentResource.getName(); - if (resourceNameCurrent.equals(resourceNameUpdated)) - return true; - // In case of CVFC type we should support the case of old VF with CVFC instances that were created without the "Cvfc" suffix - return (currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) - && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent))); - } - - private String addCvfcSuffixToResourceName(String resourceName) { - return resourceName+"Cvfc"; - } - - private Either validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) { - String resourceNameUpdated = updateInfoResource.getName(); - if (!isResourceNameEquals(currentResource, updateInfoResource)) { - if (isNested || !hasBeenCertified) { - Either validateResourceNameResponse = validateComponentName(null, updateInfoResource, null); - if (validateResourceNameResponse.isRight()) { - ResponseFormat errorResponse = validateResourceNameResponse.right().value(); - return Either.right(errorResponse); - } - validateResourceNameResponse = validateResourceNameExists(updateInfoResource); - if (validateResourceNameResponse.isRight()) { - ResponseFormat errorResponse = validateResourceNameResponse.right().value(); - return Either.right(errorResponse); - } - currentResource.setName(resourceNameUpdated); - currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); - currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); - - } else { - log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String iconUpdated = updateInfoResource.getIcon(); - String iconCurrent = currentResource.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either validateIcon = validateIcon(null, updateInfoResource, null); - if (validateIcon.isRight()) { - ResponseFormat errorResponse = validateIcon.right().value(); - return Either.right(errorResponse); - } - } else { - log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - String vendorNameUpdated = updateInfoResource.getVendorName(); - String vendorNameCurrent = currentResource.getVendorName(); - if (!vendorNameCurrent.equals(vendorNameUpdated)) { - if (!hasBeenCertified) { - Either validateVendorName = validateVendorName(null, updateInfoResource, null); - if (validateVendorName.isRight()) { - ResponseFormat errorResponse = validateVendorName.right().value(); - return Either.right(errorResponse); - } - } else { - log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) { - String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); - String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); - if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { - Either validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null); - if (validateResourceVendorModelNumber.isRight()) { - ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value(); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) { - Either validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction); - if (validateCategoryName.isRight()) { - ResponseFormat errorResponse = validateCategoryName.right().value(); - return Either.right(errorResponse); - } - if (hasBeenCertified) { - CategoryDefinition currentCategory = currentResource.getCategories().get(0); - SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0); - CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0); - SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0); - if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) { - log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - - List currentDerivedFrom = currentResource.getDerivedFrom(); - List updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } - - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); - - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - Either validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null); - if (validateDerivedFromExistsEither.isRight()) { - return validateDerivedFromExistsEither; - } - } else { - Either validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null); - - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } else { - // For derived from, we must know whether it was actually changed, - // otherwise we must do no action. - // Due to changes it inflicts on data model (remove artifacts, - // properties...), it's not like a flat field which can be - // overwritten if not changed. - // So we must indicate that derived from is not changed - updateInfoResource.setDerivedFrom(null); - } - return Either.left(true); - } - - private Either validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) { - - List currentDerivedFrom = currentResource.getDerivedFrom(); - List updatedDerivedFrom = updateInfoResource.getDerivedFrom(); - if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) { - log.trace("Update normative types"); - return Either.left(true); - } - - String derivedFromCurrent = currentDerivedFrom.get(0); - String derivedFromUpdated = updatedDerivedFrom.get(0); - - if (!derivedFromCurrent.equals(derivedFromUpdated)) { - if (!hasBeenCertified) { - Either validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null); - if (validateDerivedFromExistsEither.isRight()) { - return validateDerivedFromExistsEither; - } - } else { - Either validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null); - - if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { - log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); - return validateDerivedFromExtending; - } - } - } - return Either.left(true); - } - - private Either validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) { - - if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { - return Either.left(true); - } - - // IResourceOperation resourceOperation = getResourceOperation(); - - String templateName = resource.getDerivedFrom().get(0); - - Either dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); - log.debug("request to data model failed with error: {}", storageStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } else if (!dataModelResponse.left().value()) { - log.info("resource template with name: {}, does not exists", templateName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - - return Either.right(responseFormat); - - } - return Either.left(true); - } - - // Tal G for extending inheritance US815447 - private Either validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) { - // If updated resource is not deriving, should fail validation - /* - * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); } - */ - // If current resource is deriving from certain type and it is updated to not deriving, should fail validation - /* - * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); } - */ - String currentTemplateName = currentResource.getDerivedFrom().get(0); - String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); - - Either dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); - if (dataModelResponse.isRight()) { - StorageOperationStatus storageStatus = dataModelResponse.right().value(); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); - log.debug("request to data model failed with error: {}", storageStatus.name()); - ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource); - log.trace("audit before sending response"); - componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - if (!dataModelResponse.left().value()) { - log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null); - - return Either.right(responseFormat); - - } - return Either.left(true); - } - - public Either validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) { - log.debug("validate resource derivedFrom field"); - if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { - log.info("derived from (template) field is missing for the resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - - return Either.right(responseFormat); - } - return Either.left(true); - } - - private Either validateResourceNameExists(Resource resource) { - - Either resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType()); - if (resourceOperationResponse.isLeft()) { - if (!resourceOperationResponse.left().value()) { - return Either.left(false); - } else { - log.debug("resource with name: {}, already exists", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - return Either.right(errorResponse); - } - } - log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value())); - return Either.right(errorResponse); - } - - /* - * private Either validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List tagsList = resource.getTags(); - * - * Either validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true); - * - * } - * - * private Either validateResourceTags(List tags, String resourceName) { log.debug("validate resource tags"); boolean includesResourceName = false; int tagListSize = 0; if (tags != null && !tags.isEmpty()) { for - * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else { - * log.debug("invalid tag {}", tag); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAG)); } tagListSize += tag.length() + 1; } if (!includesResourceName) { log.debug( "tags must include resource name"); - * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize, - * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); } - * - * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); } - */ - - private Either validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) { - - List categories = resource.getCategories(); - if (categories == null || categories.size() == 0) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - if (categories.size() > 1) { - log.debug("Must be only one category for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); - return Either.right(responseFormat); - } - CategoryDefinition category = categories.get(0); - List subcategories = category.getSubcategories(); - if (subcategories == null || subcategories.size() == 0) { - log.debug("Missinig subcategory for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); - return Either.right(responseFormat); - } - if (subcategories.size() > 1) { - log.debug("Must be only one sub category for resource"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); - return Either.right(responseFormat); - } - - SubCategoryDefinition subcategory = subcategories.get(0); - - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - Either validateCategory = validateCategoryListed(category, subcategory, inTransaction); - if (validateCategory.isRight()) { - ResponseFormat responseFormat = validateCategory.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - return Either.right(responseFormat); - } - - return Either.left(true); - } - - private Either validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) { - if (category != null && subcategory != null) { - log.debug("validating resource category {} against valid categories list", category); - Either, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); - if (categories.isRight()) { - log.debug("failed to retrive resource categories from Titan"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value()); - return Either.right(responseFormat); - } - List categoryList = categories.left().value(); - for (CategoryDefinition cat : categoryList) { - if (cat.getName().equals(category.getName())) { - for (SubCategoryDefinition subcat : cat.getSubcategories()) { - if (subcat.getName().equals(subcategory.getName())) { - return Either.left(true); - } - } - log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - } - log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - return Either.left(false); - } - - public Either validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) { - String vendorRelease = resource.getVendorRelease(); - - log.debug("validate vendor relese name"); - if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { - log.info("vendor relese name is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - return Either.right(errorResponse); - } - - Either validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease); - if (validateVendorReleaseResponse.isRight()) { - ResponseFormat responseFormat = validateVendorReleaseResponse.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateVendorReleaseResponse; - } - - public Either validateVendorReleaseName(String vendorRelease) { - if (vendorRelease != null) { - if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { - log.info("vendor release exceds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateVendorRelease(vendorRelease)) { - log.info("vendor release is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); - return Either.right(errorResponse); - } - return Either.left(true); - } - return Either.left(false); - - } - - private Either validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) { - String vendorName = resource.getVendorName(); - if (!ValidationUtils.validateStringNotEmpty(vendorName)) { - log.info("vendor name is missing."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME); - componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); - return Either.right(errorResponse); - } - - Either validateVendorNameResponse = validateVendorName(vendorName); - if (validateVendorNameResponse.isRight()) { - ResponseFormat responseFormat = validateVendorNameResponse.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateVendorNameResponse; - - } - - private Either validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) { - String resourceVendorModelNumber = resource.getResourceVendorModelNumber(); - Either validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber); - if (validateResourceVendorModelNumber.isRight()) { - ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value(); - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return validateResourceVendorModelNumber; - - } - - - private Either validateVendorName(String vendorName) { - if (vendorName != null) { - if (!ValidationUtils.validateVendorNameLength(vendorName)) { - log.info("vendor name exceds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateVendorName(vendorName)) { - log.info("vendor name is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); - return Either.right(errorResponse); - } - return Either.left(true); - - } - return Either.left(false); - - } - - private Either validateResourceVendorModelNumber(String resourceVendorModelNumber) { - if (resourceVendorModelNumber.equals("")) { - return Either.left(true); - } else { - if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) { - log.info("resource vendor model number exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - return Either.right(errorResponse); - } - // resource vendor model number is currently validated as vendor name - if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) { - log.info("resource vendor model number is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - - /* - * private Either validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) { - * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse, - * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description); - * - * Either validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); } - * - * private Either validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return - * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); } - * - * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return - * Either.left(false); } - */ - - /* - * private Either validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId(); - * - * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * Either validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value(); - * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; } - * - * private Either validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse = - * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); - * - * } - */ - - /* - * private Either validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon(); - * - * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); } - * - * Either validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, - * null); } return validateIcon; - * - * } - * - * public Either validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus. - * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse = - * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false); - * - * } - */ - - private Either validateCost(User user, Resource resource, AuditingActionEnum actionEnum) { - String cost = resource.getCost(); - if (cost != null) { - - if (!ValidationUtils.validateCost(cost)) { - log.debug("resource cost is invalid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) { - log.debug("validate licenseType"); - String licenseType = resource.getLicenseType(); - if (licenseType != null) { - List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes(); - if (!licenseTypes.contains(licenseType)) { - log.debug("License type {} isn't configured"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - if (actionEnum != null) { - // In update case, no audit is required - componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); - } - return Either.right(responseFormat); - } - } - return Either.left(true); - } - - private Either processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) { - Either deleteArtifactByInterface = null; - if (updatedResource.getDerivedFrom() != null) { - log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); - log.debug("1. Removing interface artifacts from graph"); - // Remove all interface artifacts of resource - String resourceId = updatedResource.getUniqueId(); - Map interfaces = currentResource.getInterfaces(); - - if (interfaces != null) { - Collection values = interfaces.values(); - for (InterfaceDefinition interfaceDefinition : values) { - String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); - - log.trace("Starting interface artifacts removal for interface type {}", interfaceType); - Map operations = interfaceDefinition.getOperationsMap(); - if (operations != null) { - for (Entry operationEntry : operations.entrySet()) { - Operation operation = operationEntry.getValue(); - ArtifactDefinition implementation = operation.getImplementationArtifact(); - if (implementation != null) { - String uniqueId = implementation.getUniqueId(); - log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType); - // only thing that transacts and locks here - deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true); - if (deleteArtifactByInterface.isRight()) { - log.debug("Couldn't remove artifact definition with id {}", uniqueId); - if (!inTransaction) { - titanDao.rollback(); - } - return Either.right(deleteArtifactByInterface.right().value()); - } - } else { - log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey()); - } - } - } else { - log.trace("No operations found for interface type {}", interfaceType); - } - } - } - log.debug("2. Removing properties"); - Either, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); - - if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { - log.debug("Failed to remove all properties of resource"); - if (!inTransaction) - titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); - } - - } else { - log.debug("Derived from wasn't changed during update"); - } - - if (!inTransaction) - titanDao.commit(); - return Either.left(true); - - } - - /**** Auditing *******************/ - - protected static IElementOperation getElementDao(Class class1, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(class1); - } - - public ICapabilityTypeOperation getCapabilityTypeOperation() { - return capabilityTypeOperation; - } - - public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { - this.capabilityTypeOperation = capabilityTypeOperation; - } - - public Either validatePropertiesDefaultValues(Resource resource) { - log.debug("validate resource properties default values"); - Either eitherResult = Either.left(true); - List properties = resource.getProperties(); - String type = null; - String innerType = null; - if (properties != null) { - for (PropertyDefinition property : properties) { - if (!propertyOperation.isPropertyTypeValid(property)) { - log.info("Invalid type for property"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); - eitherResult = Either.right(responseFormat); - break; - } - - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - return Either.right(allDataTypes.right().value()); - } - - type = property.getType(); - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - ImmutablePair propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value()); - innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight().booleanValue()) { - log.info("Invalid inner type for property"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); - eitherResult = Either.right(responseFormat); - break; - } - } - - if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) { - log.info("Invalid default value for property"); - ResponseFormat responseFormat; - if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); - } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); - } - eitherResult = Either.right(responseFormat); - break; - - } - } - } - return eitherResult; - } - - @Override - public Either, ResponseFormat> deleteMarkedComponents() { - return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return vfComponentInstanceBusinessLogic; - } - - private String getComponentTypeForResponse(Component component) { - String componentTypeForResponse = "SERVICE"; - if (component instanceof Resource) { - componentTypeForResponse = ((Resource) component).getResourceType().name(); - } - return componentTypeForResponse; - } - - private Either, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map toscaJson, Resource resource) { - - Map groups = new HashMap(); - Either, ResponseFormat> result = Either.left(groups); - - Either, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS); - if (eitherNodesTemlates.isLeft()) { - Map jsonNodeTemplates = eitherNodesTemlates.left().value(); - - if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) { - Iterator> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); - while (nodesNameValue.hasNext()) { - Entry groupNameValue = nodesNameValue.next(); - - String groupName = groupNameValue.getKey(); - Either eitherNode = createGroupInfo(groupName, groupNameValue.getValue()); - if (eitherNode.isRight()) { - String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName(); - BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); - return Either.right(eitherNode.right().value()); - } else { - GroupDefinition groupDefinition = eitherNode.left().value(); - groups.put(groupName, groupDefinition); - } - } - } - } - - return result; - } - - private Either, ResponseFormat> createInputsFromYaml(String yamlFileName, Map toscaJson, Resource resource) { - - Either, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson); - if (inputs.isRight()) { - String message = "Failed when creating inputs: for resource:" + resource.getName(); - BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); - Map resultMap = new HashMap<>(); - return Either.left(resultMap); - - } - - Either, ResponseFormat> result = Either.left(inputs.left().value()); - - return result; - } - - @SuppressWarnings("unchecked") - private Either createGroupInfo(String groupName, Object groupTemplateJson) { - - GroupDefinition groupInfo = new GroupDefinition(); - groupInfo.setName(groupName); - Either result = Either.left(groupInfo); - - try { - if (groupTemplateJson != null && groupTemplateJson instanceof Map) { - Map groupTemplateJsonMap = (Map) groupTemplateJson; - String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - if (!StringUtils.isEmpty(groupType)) { - groupInfo.setType(groupType); - } else { - log.debug("The 'type' member is not found under group {}", groupName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName)); - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) { - Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName()); - if (members != null) { - if (members instanceof List) { - Map membersLoaded = new HashMap<>(); - List membersAsList = (List) members; - for (Object member : membersAsList) { - membersLoaded.put(member.toString(), ""); - } - groupInfo.setMembers(membersLoaded); - } else { - log.debug("The 'members' member is not of type list under group {}", groupName); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - } - } - - if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName()); - - Either, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType); - if (regResponse.isRight()) - return Either.right(regResponse.right().value()); - if (regResponse.left().value().size() > 0) { - groupInfo.convertFromGroupProperties(regResponse.left().value()); - } - } - - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group"); - log.debug("error when creating group, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - @SuppressWarnings("unchecked") - private Either, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) { - - List result = new ArrayList<>(); - - if (properties == null) { - return Either.left(result); - } - - Either groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - - if (groupTypeRes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - } - - Map gtProperties = new HashMap<>(); - GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); - - List propertiesDef = groupTypeDefinition.getProperties(); - - if (propertiesDef != null) { - gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - } - - if (properties != null) { - - if (properties instanceof Map) { - - Map props = (Map) properties; - for (Entry entry : props.entrySet()) { - - String propName = entry.getKey(); - Object value = entry.getValue(); - - PropertyDefinition gtDefinition = gtProperties.get(propName); - if (gtDefinition == null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType)); - } - - ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType()); - - String convertedValue = null; - if (value != null) { - if (type == null || value instanceof Map || value instanceof List) { - convertedValue = gson.toJson(value); - } else { - convertedValue = value.toString(); - } - } - - GroupProperty groupProperty = new GroupProperty(); - groupProperty.setValue(convertedValue); - groupProperty.setName(propName); - - log.trace("After building group property {}", groupProperty); - - result.add(groupProperty); - } - - } - - } - - return Either.left(result); - } - - public Either getLatestResourceFromCsarUuid(String csarUuid, User user) { - - // validate user - if (user != null) { - Either userValidation = validateUserExists(user, "Get resource from csar UUID", false); - if (userValidation.isRight()) { - return Either.right(userValidation.right().value()); - } - } - - // get resource from csar uuid - Either either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); - if (either.isRight()) { - ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid); - return Either.right(resp); - } - - return Either.left(either.left().value()); - } - - @Override - public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - private Either>, ResponseFormat> getValidComponentInstanceCapabilities(String resourceId, Map> defaultCapabilities, Map> uploadedCapabilities) { - ResponseFormat responseFormat; - Map> validCapabilitiesMap = new HashMap<>(); - - for (Entry> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) { - String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType(); - if (!defaultCapabilities.containsKey(capabilityType)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType); - return Either.right(responseFormat); - } else { - CapabilityDefinition defaultCapability; - if(CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())){ - defaultCapability = defaultCapabilities.get(capabilityType).get(0); - } else { - Either getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId); - if(getFullComponentRes.isRight()){ - log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId); - return Either.right(responseFormat); - } - defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); - } - if(CollectionUtils.isEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){ - log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId); - log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId); - return Either.right(responseFormat); - } - if(CollectionUtils.isNotEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){ - Either validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, uploadedCapabilitiesEntry.getValue().get(0)); - if (validationRes.isRight()) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value()); - return Either.right(responseFormat); - } - } - List validCapabilityList = new ArrayList<>(); - validCapabilityList.add(defaultCapability); - validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList); - } - } - return Either.left(validCapabilitiesMap); - } - - private Either validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { - List validProperties = new ArrayList<>(); - Map defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); - List uploadedProperties = uploadedCapability.getProperties(); - for (UploadPropInfo property : uploadedProperties) { - String propertyName = property.getName().toLowerCase(); - String propertyType = property.getType(); - ComponentInstanceProperty validProperty; - if (defaultProperties.containsKey(propertyName)) { - if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) { - return Either.right(propertyName); - } - } - validProperty = new ComponentInstanceProperty(); - validProperty.setName(propertyName); - if (property.getValue() != null) - validProperty.setValue(property.getValue().toString()); - validProperty.setDescription(property.getDescription()); - validProperty.setPassword(property.isPassword()); - validProperties.add(validProperty); - } - defaultCapability.setProperties(validProperties); - return Either.left(true); - } - - private Either>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List artifactPathAndNameList, List existingArtifactsToHandle, - Resource resource, User user) { - - EnumMap> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); - Wrapper responseWrapper = new Wrapper<>(); - Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); - ; - try { - // add all found Csar artifacts to list to upload - List artifactsToUpload = new ArrayList<>(artifactPathAndNameList); - List artifactsToUpdate = new ArrayList<>(); - List artifactsToDelete = new ArrayList<>(); - for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { - ArtifactDefinition foundArtifact; - - if (!existingArtifactsToHandle.isEmpty()) { - foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null); - if (foundArtifact != null) { - if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) { - if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { - currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); - // if current artifact already exists, but has different content, add him to the list to update - artifactsToUpdate.add(currNewArtifact); - } - // remove found artifact from the list of existing artifacts to handle, because it was already handled - existingArtifactsToHandle.remove(foundArtifact); - // and remove found artifact from the list to upload, because it should either be updated or be ignored - artifactsToUpload.remove(currNewArtifact); - } else { - log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName()); - ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), - currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType()); - AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum()); - artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null); - responseWrapper.setInnerElement(responseFormat); - break; - } - } - } - } - if (responseWrapper.isEmpty()) { - existingArtifactsToHandle.stream() - // add all artifacts which was not detected as artifact to update or to ignore to the list to delete - .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId()))); - } - if (responseWrapper.isEmpty()) { - if (!artifactsToUpload.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload); - if (!artifactsToUpdate.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate); - if (!artifactsToDelete.isEmpty()) - nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete); - } - if (!responseWrapper.isEmpty()) { - nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); - } - } catch (Exception e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); - } - return nodeTypeArtifactsToHandleRes; - } - - - private ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) { - String actualType; - String actualVfName; - String actualPreviousVfName; - if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){ - actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); - actualType = ResourceTypeEnum.VFC.name(); - } else { - actualVfName = vfResourceName; - actualType = nodeResourceType; - } - - StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = nameWithouNamespacePrefix.split("\\."); - String resourceType = findTypes[0]; - String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); - - if (actualName.startsWith(Constants.ABSTRACT)) { - toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)); - } else { - toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); - } - StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); - return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString()); - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - ///////////////////////////////////////// DataModel refactoring///////////////////////////////////////////// - @Override - public Either getUiComponentDataTransferByComponentId(String resourceId, List dataParamsToReturn) { - - ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); - - if (resourceResultEither.isRight()) { - if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to found resource with id {} ", resourceId); - Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); - } - - log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); - } - - Resource resource = resourceResultEither.left().value(); - UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn); - return Either.left(dataTransfer); - } - @Override - public Either shouldUpgradeToLatestDerived(Component clonedComponent) { - Resource resource = (Resource) clonedComponent; - if (ModelConverter.isAtomicComponent(resource.getResourceType())) { - Either shouldUpgradeToLatestDerived = toscaOperationFacade.shouldUpgradeToLatestDerived(resource); - if (shouldUpgradeToLatestDerived.isRight()) { - return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value())); - } - return Either.left(shouldUpgradeToLatestDerived.left().value()); - } else { - return super.shouldUpgradeToLatestDerived(clonedComponent); - } - } - - - -} + @Autowired + private CompositionBusinessLogic compositionBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + @Autowired + private MergeResourceBLFactory mergeResourceBLFactory; + + @Autowired + private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic; + + private Gson gson = new Gson(); + + public CsarOperation getCsarOperation() { + return csarOperation; + } + + public void setCsarOperation(CsarOperation csarOperation) { + this.csarOperation = csarOperation; + } + + public LifecycleBusinessLogic getLifecycleBusinessLogic() { + return lifecycleBusinessLogic; + } + + public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) { + this.lifecycleBusinessLogic = lifecycleBusinessLogic; + } + + public IElementOperation getElementDao() { + return elementDao; + } + + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } + + public IUserBusinessLogic getUserAdmin() { + return this.userAdmin; + } + + public void setUserAdmin(UserBusinessLogic userAdmin) { + this.userAdmin = userAdmin; + } + + public ComponentsUtils getComponentsUtils() { + return this.componentsUtils; + } + + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsBusinessLogic; + } + + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsBusinessLogic = artifactsManager; + } + + public void setPropertyOperation(IPropertyOperation propertyOperation) { + this.propertyOperation = propertyOperation; + } + + public ApplicationDataTypeCache getApplicationDataTypeCache() { + return applicationDataTypeCache; + } + + public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) { + this.applicationDataTypeCache = applicationDataTypeCache; + } + + /** + * the method returns a list of all the resources that are certified, the + * returned resources are only abstract or only none abstract according to + * the given param + * + * @param getAbstract + * @param userId TODO + * @return + */ + public Either, ResponseFormat> getAllCertifiedResources(boolean getAbstract, + HighestFilterEnum highestFilter, String userId) { + Either resp = validateUserExists(userId, "get All Certified Resources", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Boolean isHighest = null; + switch (highestFilter) { + case ALL: + break; + case HIGHEST_ONLY: + isHighest = true; + break; + case NON_HIGHEST_ONLY: + isHighest = false; + break; + default: + break; + } + Either, StorageOperationStatus> getResponse = toscaOperationFacade + .getAllCertifiedResources(getAbstract, isHighest); + + if (getResponse.isRight()) { + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value()))); + } + + return Either.left(getResponse.left().value()); + } + + public Either, ResponseFormat> validateResourceNameExists(String resourceName, + ResourceTypeEnum resourceTypeEnum, String userId) { + + Either resp = validateUserExists(userId, "validate Resource Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either dataModelResponse = toscaOperationFacade + .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE); + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + public Either createResource(Resource resource, AuditingActionEnum auditingAction, + User user, Map csarUIPayload, String payloadName) { + Either createResourceResponse = validateResourceBeforeCreate(resource, user, false); + if (createResourceResponse.isRight()) { + return createResourceResponse; + } + + // Creating resource either by DAO or from CSAR + String csarUUID = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + } else { + csarUUID = payloadName; + } + if (csarUUID != null && !csarUUID.isEmpty()) { + // check if VF with the same Csar UUID or with he same name already + // exists + Either validateCsarUuidUniquenessRes = toscaOperationFacade + .validateCsarUuidUniqueness(csarUUID); + if (validateCsarUuidUniquenessRes.isRight()) { + log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, + resource.getSystemName()); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value()))); + } + + Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value(); + if (existingResourceRes.intValue() > 0) { + log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", + resource.getSystemName(), csarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, + csarUUID); + componentsUtils.auditResource(errorResponse, user, resource, auditingAction); + return Either.right(errorResponse); + } + + log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); + createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID); + return createResourceResponse; + } + + return createResourceByDao(resource, user, auditingAction, false, false); + } + + public Either validateAndUpdateResourceFromCsar(Resource resource, User user, + Map csarUIPayload, String payloadName, String resourceUniqueId) { + Either updateResourceResponse = null; + Either validateResourceResponse = null; + Wrapper responseWrapper = new Wrapper(); + String csarUUID = null; + String csarVersion = null; + if (payloadName == null) { + csarUUID = resource.getCsarUUID(); + csarVersion = resource.getCsarVersion(); + } else { + csarUUID = payloadName; + } + if (csarUUID != null && !csarUUID.isEmpty()) { + Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId); + if (responseWrapper.isEmpty()) { + validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user); + } + if (responseWrapper.isEmpty()) { + validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user); + } + if (responseWrapper.isEmpty()) { + if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) { + overrideImmutableMetadata(oldResource, resource); + } + validateResourceResponse = validateResourceBeforeCreate(resource, user, false); + if (validateResourceResponse.isRight()) { + responseWrapper.setInnerElement(validateResourceResponse.right().value()); + } + } + if (responseWrapper.isEmpty()) { + String oldCsarVersion = oldResource.getCsarVersion(); + log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, + resourceUniqueId); + // (on boarding flow): If the update includes same csarUUID and + // same csarVersion as already in the VF - no need to import the + // csar (do only metadata changes if there are). + if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) { + updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, + false); + } else { + updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID); + } + } + } else { + log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, + resource.getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + if (responseWrapper.isEmpty()) { + return updateResourceResponse; + } + return Either.right(responseWrapper.getInnerElement()); + } + + private void validateCsarIsNotAlreadyUsed(Wrapper responseWrapper, Resource oldResource, + Resource resource, String csarUUID, User user) { + // (on boarding flow): If the update includes a csarUUID: verify this + // csarUUID is not in use by another VF, If it is - use same error as + // above: + // "Error: The VSP with UUID %1 was already imported for VF %2. Please + // select another or update the existing VF." %1 - csarUUID, %2 - VF + // name + Either resourceLinkedToCsarRes = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName()); + if (resourceLinkedToCsarRes.isRight()) { + if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) { + log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, + resource.getSystemName()); + responseWrapper.setInnerElement(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value()))); + } + } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) + && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, + resourceLinkedToCsarRes.left().value().getName()); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + responseWrapper.setInnerElement(errorResponse); + } + } + + private void validateCsarUuidMatching(Wrapper responseWrapper, Resource resource, + Resource oldResource, String csarUUID, String resourceUniqueId, User user) { + // (on boarding flow): If the update includes csarUUID which is + // different from the csarUUID of the VF - fail with + // error: "Error: Resource %1 cannot be updated using since it is linked + // to a different VSP" %1 - VF name + String oldCsarUUID = oldResource.getCsarUUID(); + if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) { + log.debug( + "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", + resourceUniqueId, csarUUID, oldCsarUUID); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID); + componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + responseWrapper.setInnerElement(errorResponse); + } + } + + private Resource getResourceByUniqueId(Wrapper responseWrapper, String resourceUniqueId) { + Either oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId); + if (oldResourceRes.isRight()) { + log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, + oldResourceRes.right().value()); + responseWrapper.setInnerElement(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value()))); + return null; + } + return oldResourceRes.left().value(); + } + + private void overrideImmutableMetadata(Resource oldRresource, Resource resource) { + resource.setName(oldRresource.getName()); + resource.setIcon(oldRresource.getIcon()); + resource.setTags(oldRresource.getTags()); + resource.setVendorName(oldRresource.getVendorName()); + resource.setCategories(oldRresource.getCategories()); + resource.setDerivedFrom(oldRresource.getDerivedFrom()); + } + + private Either updateResourceFromCsar(Resource oldRresource, Resource newRresource, + User user, AuditingActionEnum updateResource, boolean inTransaction, + Either, StorageOperationStatus> csarUIPayload, String csarUUID) { + + // check state + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) { + if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) { + log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", + oldRresource.getLastUpdaterUserId(), user.getUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + String lockedResourceId = oldRresource.getUniqueId(); + List createdArtifacts = new ArrayList<>(); + + Either, StorageOperationStatus> csar = null; + if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { + csar = csarUIPayload; + } else { + csar = csarOperation.getCsar(csarUUID, user); + } + if (csar.isRight()) { + log.debug("Failed to get csar for casrUUID{} ", csarUUID); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value()))); + } + + Either, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, + user, csarUUID, csar); + if (toscaYamlCsarStatus.isRight()) { + return Either.right(toscaYamlCsarStatus.right().value()); + } + Either checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), + csarUUID, componentsUtils); + if (checksum.isRight()) { + log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value()); + return Either.right(checksum.right().value()); + } + if (!checksum.left().value().equals( + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) { + log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID, + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition() + .getImportedToscaChecksum(), + checksum.left().value()); + oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition() + .setImportedToscaChecksum(checksum.left().value()); + } + + Either lockResult = lockComponent(lockedResourceId, oldRresource, + "update Resource From Csar"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + + String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); + CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, + true); + Map nodeTypesInfo = extractNodeTypesInfo(csarInfo); + Either result = null; + + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, oldRresource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + return result; + } + Map>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes + .left().value(); + try { + result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, yamlFileName, + yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false); + + } finally { + if (result == null || result.isRight()) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + return result; + + } + + private Either updateResourceFromYaml(Resource oldRresource, Resource newRresource, + AuditingActionEnum updateResource, List createdArtifacts, + String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, + Map>> nodeTypesArtifactsToHandle, + String nodeName, boolean isNested) { + Either result; + Either, ResponseFormat> parseNodeTypeInfoYamlEither; + boolean inTransaction = true; + boolean shouldLock = false; + + Either, ResponseFormat> prepareForUpdate; + Resource preparedResource; + Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml( + yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), + nodeTypesInfo, nodeName); + if (uploadComponentInstanceInfoMap.isRight()) { + ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, updateResource); + result = Either.right(responseFormat); + return result; + } + + Map instances = uploadComponentInstanceInfoMap.left().value() + .getInstances(); + + prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), + inTransaction, shouldLock, isNested); + if (prepareForUpdate.isRight()) { + log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value()); + result = Either.right(prepareForUpdate.right().value()); + return result; + } + preparedResource = prepareForUpdate.left().value().left; + + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); + + Either genericResourceEither = handleResourceGenericType(preparedResource); + if (genericResourceEither.isRight()) { + log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value()); + ResponseFormat responseFormat = genericResourceEither.right().value(); + componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + return Either.right(responseFormat); + } + + parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, + shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); + if (parseNodeTypeInfoYamlEither.isRight()) { + ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + + Map inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); + Either createInputsOnResource = createInputsOnResource(preparedResource, + csarInfo.getModifier(), inputs, inTransaction); + if (createInputsOnResource.isRight()) { + log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value()); + ResponseFormat responseFormat = createInputsOnResource.right().value(); + componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + preparedResource = createInputsOnResource.left().value(); + + Either createResourcesInstancesEither = createResourceInstances( + csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, + csarInfo.getCreatedNodes()); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create resource instances status is {}", + createResourcesInstancesEither.right().value()); + ResponseFormat responseFormat = createResourcesInstancesEither.right().value(); + componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), + preparedResource, updateResource); + result = Either.right(responseFormat); + return result; + } + preparedResource = createResourcesInstancesEither.left().value(); + + createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, + preparedResource, instances); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create relation between resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = Either.right(createResourcesInstancesEither.right().value()); + return result; + } + + preparedResource = createResourcesInstancesEither.left().value(); + + Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), + preparedResource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { + + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + // add groups to resource + Map groups; + + if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left().value(); + } else { + groups = uploadComponentInstanceInfoMap.left().value().getGroups(); + } + Either updatedGroupsOnResource = updateGroupsOnResource(preparedResource, + csarInfo.getModifier(), groups); + if (updatedGroupsOnResource.isRight()) { + + return updatedGroupsOnResource; + } + preparedResource = updatedGroupsOnResource.left().value(); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToHandle); + + Either updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, + csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (updateArtifactsEither.isRight()) { + log.debug("failed to update artifacts {}", updateArtifactsEither.right().value()); + result = Either.right(updateArtifactsEither.right().value()); + return result; + } + preparedResource = updateArtifactsEither.left().value(); + + ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource); + if (mergingPropsAndInputsStatus != ActionStatus.OK) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, + preparedResource); + return Either.right(responseFormat); + } + + Either, ResponseFormat> eitherSetPosition = compositionBusinessLogic + .setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); + result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) + : Either.left(preparedResource); + + return result; + + } + + private Either createOrUpdateArtifacts(ArtifactOperationEnum operation, List createdArtifacts, + String yamlFileName, CsarInfo csarInfo, Resource preparedResource, + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { + + String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName(); + Resource resource = preparedResource; + + Map>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts + .getNodeTypesArtifactsToHandle(); + if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) { + if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) { + Either, ResponseFormat> handleNodeTypeArtifactsRes = + handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); + if (handleNodeTypeArtifactsRes.isRight()) { + return Either.right(handleNodeTypeArtifactsRes.right().value()); + } + } + } else { + Either createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); + log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); + if (createdCsarArtifactsEither.isRight()) { + return createdCsarArtifactsEither; + + } + resource = createdCsarArtifactsEither.left().value(); + } + return Either.left(resource); + } + + private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { + Either mergeResourceBLEither = mergeResourceBLFactory + .getInstance(oldResource, newResource); + if (mergeResourceBLEither.isRight()) { + return mergeResourceBLEither.right().value(); + } + MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value(); + return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource); + } + + private Either handleResourceGenericType(Resource resource) { + Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) { + return genericResourceEither; + } + if (resource.shouldGenerateInputs()) { + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + } + return genericResourceEither; + } + + private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle( + Map nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) { + + Map> extractedVfcsArtifacts = CsarUtils + .extractVfcsArtifactsFromCsar(csarInfo.getCsar()); + Map>> nodeTypesArtifactsToHandle = new HashMap<>(); + Either>>, ResponseFormat> nodeTypesArtifactsToHandleRes; + + try { + nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); + Map> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, + oldResource.getName(), csarInfo); + Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes; + EnumMap> curNodeTypeArtifactsToHandle = null; + log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", + oldResource.getName(), csarInfo.getCsarUUID()); + + for (Entry> currVfcToscaNameEntry : extractedVfcToscaNames + .entrySet()) { + String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft(); + String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight(); + String currNamespace = currVfcToscaNameEntry.getKey(); + log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName); + + Either curVfcRes = toscaOperationFacade + .getLatestByToscaResourceName(currVfcToscaName); + Resource curNodeType = null; + if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { + curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName); + } + if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, + curVfcRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), + csarInfo.getCsarUUID()); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, AuditingActionEnum.CREATE_RESOURCE); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + break; + } else if (curVfcRes.isLeft()) { + curNodeType = curVfcRes.left().value(); + } + if (!MapUtils.isEmpty(extractedVfcsArtifacts)) { + List currArtifacts = new ArrayList<>(); + if (extractedVfcsArtifacts.containsKey(currNamespace)) { + handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace)); + } + curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts); + if (curNodeTypeArtifactsToHandleRes.isRight()) { + nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value()); + break; + } + curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value(); + + } else if (curNodeType != null) { + // delete all artifacts if have not received artifacts from + // csar + curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + List artifactsToDelete = new ArrayList<>(); + // delete all informational artifacts + artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream() + .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(Collectors.toList())); + // delete all deployment artifacts + artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values()); + if (!artifactsToDelete.isEmpty()) { + curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + } + if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) { + nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + nodeTypesArtifactsToHandleRes = Either.right(responseFormat); + log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e); + } + return nodeTypesArtifactsToHandleRes; + } + + private Either>, ResponseFormat> findNodeTypeArtifactsToHandle( + Resource curNodeType, List extractedArtifacts) { + + Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = null; + EnumMap> nodeTypeArtifactsToHandle = null; + Wrapper responseWrapper = new Wrapper<>(); + try { + List artifactsToUpload = new ArrayList<>(extractedArtifacts); + List artifactsToUpdate = new ArrayList<>(); + List artifactsToDelete = new ArrayList<>(); + if (curNodeType != null) { + Map existingArtifacts = new HashMap<>(); + if (curNodeType.getDeploymentArtifacts() != null) { + existingArtifacts.putAll(curNodeType.getDeploymentArtifacts()); + } + if (curNodeType.getArtifacts() != null) { + existingArtifacts + .putAll(curNodeType.getArtifacts().entrySet().stream() + .filter(e -> e.getValue() + .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); + } + for (ArtifactDefinition currNewArtifact : extractedArtifacts) { + ArtifactDefinition foundArtifact; + + if (!existingArtifacts.isEmpty()) { + foundArtifact = existingArtifacts.values().stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() + .orElse(null); + if (foundArtifact != null) { + if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) { + if (!foundArtifact.getArtifactChecksum() + .equals(currNewArtifact.getArtifactChecksum())) { + foundArtifact.setPayload(currNewArtifact.getPayloadData()); + foundArtifact.setPayloadData( + Base64.encodeBase64String(currNewArtifact.getPayloadData())); + foundArtifact.setArtifactChecksum(GeneralUtility + .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData())); + artifactsToUpdate.add(foundArtifact); + } + existingArtifacts.remove(foundArtifact.getArtifactLabel()); + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", + currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), + foundArtifact.getArtifactType()); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + artifactsToDelete.addAll(existingArtifacts.values()); + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) { + nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + /** + * Changes resource life cycle state to checked out + * + * @param resource + * @param user + * @param inTransaction + * @return + */ + private Either checkoutResource(Resource resource, User user, boolean inTransaction) { + Either checkoutResourceRes; + try { + if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState() + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "************* Going to change life cycle state of resource {} to not certified checked out. ", + resource.getName()); + Either checkoutRes = lifecycleBusinessLogic.changeComponentState( + resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("certification on import", + LifecycleChanceActionEnum.CREATE_FROM_CSAR), + inTransaction, true); + if (checkoutRes.isRight()) { + log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", + resource.getComponentType().getNodeType(), resource.getUniqueId(), + checkoutRes.right().value().getStatus()); + checkoutResourceRes = Either.right(checkoutRes.right().value()); + } else { + checkoutResourceRes = Either.left((Resource) checkoutRes.left().value()); + } + } else { + checkoutResourceRes = Either.left(resource); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + checkoutResourceRes = Either.right(responseFormat); + log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), + e); + } + return checkoutResourceRes; + } + + /** + * Handles Artifacts of NodeType + * + * @param nodeTypeResource + * @param nodeTypeArtifactsToHandle + * @param user + * @param inTransaction + * @return + */ + public Either, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, + Map> nodeTypeArtifactsToHandle, + List createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) { + Either, ResponseFormat> handleNodeTypeArtifactsRequestRes; + Either, ResponseFormat> handleNodeTypeArtifactsRes = null; + Either changeStateResponse; + try { + changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction); + if (changeStateResponse.isRight()) { + return Either.right(changeStateResponse.right().value()); + } + nodeTypeResource = changeStateResponse.left().value(); + + List handledNodeTypeArtifacts = new ArrayList<>(); + log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); + for (Entry> curOperationEntry : nodeTypeArtifactsToHandle + .entrySet()) { + ArtifactOperationEnum curOperation = curOperationEntry.getKey(); + List curArtifactsToHandle = curOperationEntry.getValue(); + if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { + log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), + nodeTypeResource.getName()); + handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic + .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, + createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, + ignoreLifecycleState, curOperation), + false, inTransaction); + if (handleNodeTypeArtifactsRequestRes.isRight()) { + handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value()); + break; + } + if (ArtifactOperationEnum.isCreateOrLink(curOperation)) { + createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value()); + } + } + if (handleNodeTypeArtifactsRes == null) { + handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + handleNodeTypeArtifactsRes = Either.right(responseFormat); + log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e); + } + return handleNodeTypeArtifactsRes; + } + + private Map> extractVfcToscaNames(Map nodeTypesInfo, + String vfResourceName, CsarInfo csarInfo) { + Map> vfcToscaNames = new HashMap<>(); + + Map nodes = extractAllNodes(nodeTypesInfo, csarInfo); + if (!nodes.isEmpty()) { + Iterator> nodesNameEntry = nodes.entrySet().iterator(); + while (nodesNameEntry.hasNext()) { + Entry nodeType = nodesNameEntry.next(); + ImmutablePair toscaResourceName = buildNestedToscaResourceName( + ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey()); + vfcToscaNames.put(nodeType.getKey(), toscaResourceName); + } + } + for (NodeTypeInfo cvfc : nodeTypesInfo.values()) { + vfcToscaNames.put(cvfc.getType(), + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType())); + } + return vfcToscaNames; + } + + private Map extractAllNodes(Map nodeTypesInfo, CsarInfo csarInfo) { + Map nodes = new HashMap<>(); + for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) { + extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate()); + } + extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate()); + return nodes; + } + + private void extractNodeTypes(Map nodes, Map mappedToscaTemplate) { + Either, ResultStatusEnum> eitherNodeTypes = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (eitherNodeTypes.isLeft()) { + nodes.putAll(eitherNodeTypes.left().value()); + } + } + + public Either createResourceFromCsar(Resource resource, User user, + Either, StorageOperationStatus> csarUIPayload, String csarUUID) { + log.trace("************* created successfully from YAML, resource TOSCA "); + + Either, StorageOperationStatus> csar = null; + if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) { + csar = csarUIPayload; + } else { + csar = csarOperation.getCsar(csarUUID, user); + } + + Either, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, + csarUUID, csar); + if (toscaYamlCsarStatus.isRight()) { + return Either.right(toscaYamlCsarStatus.right().value()); + } + Either toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), + csarUUID, componentsUtils); + if (toscaYamlChecksum.isRight()) { + log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, + toscaYamlChecksum.right().value()); + return Either.right(toscaYamlChecksum.right().value()); + } + resource.getComponentMetadataDefinition().getMetadataDataDefinition() + .setImportedToscaChecksum(toscaYamlChecksum.left().value()); + + String yamlFileName = toscaYamlCsarStatus.left().value().getKey(); + String yamlFileContents = toscaYamlCsarStatus.left().value().getValue(); + log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents); + + CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, + false); + Map nodeTypesInfo = extractNodeTypesInfo(csarInfo); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, resource); + if (findNodeTypesArtifactsToHandleRes.isRight()) { + log.debug("failed to find node types for update with artifacts during import csar {}. ", + csarInfo.getCsarUUID()); + return Either.right(findNodeTypesArtifactsToHandleRes.right().value()); + } + Either createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, + yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, + null); + if (createResourceFromYaml.isRight()) { + log.debug("Couldn't create resource from YAML"); + return Either.right(createResourceFromYaml.right().value()); + } + + Resource vfResource = createResourceFromYaml.left().value(); + log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", + vfResource.getToscaResourceName()); + return Either.left(vfResource); + } + + private Map extractNodeTypesInfo(CsarInfo csarInfo) { + Map nodeTypesInfo = new HashMap<>(); + List> globalSubstitutes = new ArrayList<>(); + for (Map.Entry entry : csarInfo.getCsar().entrySet()) { + extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry); + } + if (CollectionUtils.isNotEmpty(globalSubstitutes)) { + setDerivedFrom(nodeTypesInfo, globalSubstitutes); + } + markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo); + return nodeTypesInfo; + } + + @SuppressWarnings("unchecked") + private void setDerivedFrom(Map nodeTypesInfo, + List> globalSubstitutes) { + for (Map.Entry entry : globalSubstitutes) { + String yamlFileContents = new String(entry.getValue()); + Map mappedToscaTemplate = (Map) new Yaml().load(yamlFileContents); + Either nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP); + if (nodeTypesEither.isLeft()) { + Map nodeTypes = (Map) nodeTypesEither.left().value(); + for (Entry nodeType : nodeTypes.entrySet()) { + Map nodeTypeMap = (Map) nodeType.getValue(); + if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) { + if (nodeTypesInfo.containsKey(nodeType.getKey())) { + NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey()); + List derivedFrom = new ArrayList<>(); + derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName())); + nodeTypeInfo.setDerivedFrom(derivedFrom); + } + } + } + } + } + } + + @SuppressWarnings("unchecked") + private void extractNodeTypeInfo(Map nodeTypesInfo, + List> globalSubstitutes, Map.Entry entry) { + if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) { + if (!isGlobalSubstitute(entry.getKey())) { + String yamlFileContents = new String(entry.getValue()); + Map mappedToscaTemplate = (Map) new Yaml().load(yamlFileContents); + Either substitutionMappingsEither = ImportUtils.findToscaElement( + mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP); + if (substitutionMappingsEither.isLeft()) { + Map substitutionMappings = (Map) substitutionMappingsEither.left() + .value(); + if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) { + NodeTypeInfo nodeTypeInfo = new NodeTypeInfo(); + nodeTypeInfo.setType( + (String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName())); + nodeTypeInfo.setTemplateFileName(entry.getKey()); + nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate); + nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo); + } + } + } else { + globalSubstitutes.add(entry); + } + } + } + + @SuppressWarnings("unchecked") + private void markNestedVfc(Map mappedToscaTemplate, Map nodeTypesInfo) { + Either nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP); + if (nodeTemplatesEither.isLeft()) { + Map nodeTemplates = (Map) nodeTemplatesEither.left().value(); + for (Entry nodeTemplateEntry : nodeTemplates.entrySet()) { + Map nodeTemplate = (Map) nodeTemplateEntry.getValue(); + if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName()); + if (nodeTypesInfo.containsKey(type)) { + NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type); + nodeTypeInfo.setNested(true); + } + } + } + } + } + + private boolean isGlobalSubstitute(String fileName) { + return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) + || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE); + } + + private Either, ResponseFormat> validateAndParseCsar(Resource resource, User user, + String csarUUID, Either, StorageOperationStatus> csar) { + if (csar.isRight()) { + StorageOperationStatus value = csar.right().value(); + log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + + Either validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), + csarUUID, componentsUtils); + if (validateCsarStatus.isRight()) { + ResponseFormat responseFormat = validateCsarStatus.right().value(); + log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + + Either, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils + .getToscaYaml(csar.left().value(), csarUUID, componentsUtils); + + if (toscaYamlCsarStatus.isRight()) { + ResponseFormat responseFormat = toscaYamlCsarStatus.right().value(); + log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + return toscaYamlCsarStatus; + } + + private Either validateResourceBeforeCreate(Resource resource, User user, + boolean inTransaction) { + log.trace("validating resource before create"); + Either eitherCreator = validateUser(user, "Create Resource", resource, + AuditingActionEnum.CREATE_RESOURCE, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user.copyData(eitherCreator.left().value()); + + // validate user role + Either validateRes = validateUserRole(user, resource, new ArrayList(), + AuditingActionEnum.CREATE_RESOURCE, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + // VF / PNF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(resource)) { + Either validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, + AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + } + return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null); + + } + + // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, + // nodeTypesArtifactsToCreate, true, false, null + private Either createResourceFromYaml(Resource resource, String topologyTemplateYaml, + String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { + + List createdArtifacts = new ArrayList(); + log.trace("************* createResourceFromYaml before parse yaml "); + Either parseResourceInfoFromYamlEither = parseResourceInfoFromYaml( + yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, + nodeName); + if (parseResourceInfoFromYamlEither.isRight()) { + ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + log.trace("************* createResourceFromYaml after parse yaml "); + ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value(); + log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo); + log.trace("************* createResourceFromYaml before create "); + Either createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, + parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, + nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + log.trace("************* createResourceFromYaml after create "); + if (createdResourceResponse.isRight()) { + ResponseFormat responseFormat = createdResourceResponse.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + return createdResourceResponse; + + } + + public Either, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, + Resource resource, Map mappedToscaTemplate, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, + CsarInfo csarInfo) { + + Either tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, + ToscaTagNamesEnum.TOSCA_VERSION); + if (tosca_version.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + return Either.right(responseFormat); + } + Either, ResultStatusEnum> eitherNodeTypes = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + Either, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); + Map mapToConvert = new HashMap(); + mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value()); + Resource vfcCreated = null; + if (eitherNodeTypes.isLeft()) { + Iterator> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry nodeType = nodesNameValue.next(); + Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null + || nodeTypesArtifactsToHandle.isEmpty() ? null + : nodeTypesArtifactsToHandle.get(nodeType.getKey()); + + if (nodeTypesInfo.containsKey(nodeType.getKey())) { + log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); + Either handleNeatedVfcYaml = handleNestedVfc(resource, + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeType.getKey()); + log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); + if (handleNeatedVfcYaml.isRight()) { + return Either.right(handleNeatedVfcYaml.right().value()); + } + vfcCreated = handleNeatedVfcYaml.left().value(); + } else if (csarInfo.getCreatedNodesToscaResourceNames() != null + && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + log.trace("************* Going to create node {}", nodeType.getKey()); + Either, ResponseFormat> resourceCreated = this + .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, + resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, + csarInfo, true); + log.debug("************* Finished to create node {}", nodeType.getKey()); + + if (resourceCreated.isRight()) { + return Either.right(resourceCreated.right().value()); + } + vfcCreated = resourceCreated.left().value().getLeft(); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), + vfcCreated.getToscaResourceName()); + } + if (vfcCreated != null) { + csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); + } + mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName()); + } + } + return result; + } + + private Either handleNestedVfc(Resource resource, + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName) { + + Either handleNestedVfcRes = Either.left(resource); + String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); + Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); + + log.debug("************* Going to create node types from yaml {}", yamlName); + Either, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList( + yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo); + if (createNodeTypesRes.isRight()) { + log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, + createNodeTypesRes.right().value()); + return Either.right(createNodeTypesRes.right().value()); + } + log.debug("************* Finished to create node types from yaml {}", yamlName); + + if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { + log.debug("************* Going to handle complex VFC from yaml {}", yamlName); + handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo, nodeName, yamlName); + } + return handleNestedVfcRes; + } + + private Either handleComplexVfc(Resource resource, + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName) { + + Either result = null; + Resource oldComplexVfc = null; + Resource newComplexVfc = null; + + Either buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); + if (buildCvfcRes.isRight()) { + log.debug("Failed to validate complex VFC for node {}. ", nodeName); + result = buildCvfcRes; + } + if (result == null) { + newComplexVfc = buildCvfcRes.left().value(); + Either oldComplexVfcRes = toscaOperationFacade + .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { + oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), + nodeName).getRight()); + } + if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", + newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } else if (oldComplexVfcRes.isLeft()) { + log.debug("validate derived before update"); + Either eitherValidation = validateNestedDerivedFromDuringUpdate( + oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + if (eitherValidation.isLeft()) { + oldComplexVfc = oldComplexVfcRes.left().value(); + } + } + } + if (result == null) { + result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, + oldComplexVfc, newComplexVfc); + } + if (result.isLeft()) { + newComplexVfc = result.left().value(); + csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( + "certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR); + log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); + result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, + true); + if (result.isRight()) { + log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName()); + } + } + if (result.isLeft()) { + csarInfo.getCreatedNodes().put(nodeName, result.left().value()); + csarInfo.getCvfcToCreateQueue().remove(); + } + return result; + } + + private Either handleComplexVfc( + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + + Either handleComplexVfcRes; + Map mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); + String yamlContent = new String(csarInfo.getCsar().get(yamlName)); + Map newNodeTypesInfo = nodesInfo.entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy())); + markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); + if (oldComplexVfc == null) { + handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, + csarInfo, nodesArtifactsToHandle, false, true, nodeName); + if (handleComplexVfcRes.isRight()) { + log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName); + } + } else { + handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, + newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + if (handleComplexVfcRes.isRight()) { + log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName); + } + } + return handleComplexVfcRes; + } + + private Either buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, + Map nodesInfo) { + + Either result = null; + Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo); + log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName()); + + if (!csarInfo.getCvfcToCreateQueue().contains(nodeName)) { + csarInfo.getCvfcToCreateQueue().add(nodeName); + } else { + log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), + csarInfo.getVfResourceName()); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, + csarInfo.getVfResourceName(), complexVfc.getName())); + } + if (result == null) { + result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), + AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo); + if (result.isRight()) { + log.debug("Failed to validate complex VFC {}. ", complexVfc.getName()); + } + } + return result; + } + + private String getNodeTypeActualName(String fullName) { + String nameWithouNamespacePrefix = fullName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + return nameWithouNamespacePrefix.substring(resourceType.length()); + } + + private Either, ResponseFormat> createNodeTypeResourceFromYaml( + String yamlName, Entry nodeNameValue, User user, Map mapToConvert, + Resource resourceVf, boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { + + Either resourceMetaData = fillResourceMetadata(yamlName, resourceVf, + nodeNameValue.getKey(), user); + if (resourceMetaData.isRight()) { + return Either.right(resourceMetaData.right().value()); + } + String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, + resourceMetaData.left().value().getResourceType(), csarInfo); + + Either eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, + AuditingActionEnum.CHECKIN_RESOURCE, true); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, + nodeNameValue.getKey(), isNested); + } + + private String buildNodeTypeYaml(Entry nodeNameValue, Map mapToConvert, + String nodeResourceType, CsarInfo csarInfo) { + // We need to create a Yaml from each node_types in order to create + // resource from each node type using import normative flow. + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + + Map node = new HashMap<>(); + node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()) + .getLeft(), nodeNameValue.getValue()); + mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node); + + return yaml.dumpAsMap(mapToConvert); + } + + public Either validateResourceCreationFromNodeType(Resource resource, User creator) { + + Either validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, + resource, AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + return Either.left(true); + } + + public Either, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, + UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + String nodeName, boolean isNested) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", + LifecycleChanceActionEnum.CREATE_FROM_CSAR); + Function> validator = (resource) -> this + .validateResourceCreationFromNodeType(resource, creator); + return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, + lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, + nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested); + } + + private Either fillResourceMetadata(String yamlName, Resource resourceVf, + String nodeName, User user) { + UploadResourceInfo resourceMetaData = new UploadResourceInfo(); + + // validate nodetype name prefix + if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) { + log.debug("invalid nodeName:{} does not start with {}.", nodeName, + Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, resourceMetaData.getName(), nodeName); + return Either.right(responseFormat); + } + + String actualName = this.getNodeTypeActualName(nodeName); + String namePrefix = nodeName.replace(actualName, ""); + String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + + // if we import from csar, the node_type name can be + // org.openecomp.resource.abstract.node_name - in this case we always + // create a vfc + if (resourceType.equals(Constants.ABSTRACT)) { + resourceType = ResourceTypeEnum.VFC.name().toLowerCase(); + } + // validating type + if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) { + log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), + ResourceTypeEnum.values()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, resourceMetaData.getName(), nodeName); + return Either.right(responseFormat); + } + + // Setting name + resourceMetaData.setName(resourceVf.getSystemName() + actualName); + + // Setting type from name + String type = resourceType.toUpperCase(); + resourceMetaData.setResourceType(type); + + resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION); + resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON); + resourceMetaData.setContactId(user.getUserId()); + resourceMetaData.setVendorName(resourceVf.getVendorName()); + resourceMetaData.setVendorRelease(resourceVf.getVendorRelease()); + + // Setting tag + List tags = new ArrayList<>(); + tags.add(resourceMetaData.getName()); + resourceMetaData.setTags(tags); + + // Setting category + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List categories = new ArrayList<>(); + categories.add(category); + resourceMetaData.setCategories(categories); + + return Either.left(resourceMetaData); + } + + private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, + Map nodesInfo) { + Resource cvfc = new Resource(); + NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName); + cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName)); + cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName())); + cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName())); + cvfc.setResourceType(ResourceTypeEnum.CVFC); + cvfc.setAbstract(true); + cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom()); + cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION); + cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON); + cvfc.setContactId(csarInfo.getModifier().getUserId()); + cvfc.setCreatorUserId(csarInfo.getModifier().getUserId()); + cvfc.setVendorName(resourceVf.getVendorName()); + cvfc.setVendorRelease(resourceVf.getVendorRelease()); + cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber()); + cvfc.setToscaResourceName( + buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName) + .getLeft()); + cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + + List tags = new ArrayList<>(); + tags.add(cvfc.getName()); + cvfc.setTags(tags); + + CategoryDefinition category = new CategoryDefinition(); + category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME); + SubCategoryDefinition subCategory = new SubCategoryDefinition(); + subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY); + category.addSubCategory(subCategory); + List categories = new ArrayList<>(); + categories.add(category); + cvfc.setCategories(categories); + + cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT); + cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + + return cvfc; + } + + private String buildCvfcName(String resourceVfName, String nodeName) { + String nameWithouNamespacePrefix = nodeName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1); + return addCvfcSuffixToResourceName(resourceName); + } + + private Either createResourceAndRIsFromYaml(String yamlName, Resource resource, + ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, + List createdArtifacts, String topologyTemplateYaml, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { + + boolean result = true; + List nodeTypesNewCreatedArtifacts = new ArrayList<>(); + + if (shouldLock) { + Either lockResult = lockComponentByName(resource.getSystemName(), resource, + "Create Resource"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + return Either.right(responseFormat); + } + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + log.trace("************* createResourceFromYaml before full create resource {}", yamlName); + Either genericResourceEither = fetchAndSetDerivedFromGenericType(resource); + if (genericResourceEither.isRight()) { + result = false; + return genericResourceEither; + } + Either createResourcesEither = createResourceTransaction(resource, + csarInfo.getModifier(), isNormative, inTransaction); + log.trace("************* createResourceFromYaml after full create resource {}", yamlName); + if (createResourcesEither.isRight()) { + result = false; + return createResourcesEither; + } + resource = createResourcesEither.left().value(); + // add groups to resource + log.trace("************* Going to add inputs from yaml {}", yamlName); + if (resource.shouldGenerateInputs()) + generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value()); + + Map inputs = parsedToscaYamlInfo.getInputs(); + Either createInputsOnResource = createInputsOnResource(resource, + csarInfo.getModifier(), inputs, inTransaction); + if (createInputsOnResource.isRight()) { + result = false; + return createInputsOnResource; + } + resource = createInputsOnResource.left().value(); + log.trace("************* Finish to add inputs from yaml {}", yamlName); + + Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo + .getInstances(); + log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); + + createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, + actionEnum, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypesArtifactsToCreate, nodeName); + log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); + if (createResourcesEither.isRight()) { + result = false; + return createResourcesEither; + } + + resource = createResourcesEither.left().value(); + // validate update vf module group names + Either, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic + .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); + if (validateUpdateVfGroupNamesRes.isRight()) { + result = false; + return Either.right(validateUpdateVfGroupNamesRes.right().value()); + } + // add groups to resource + Map groups; + log.trace("************* Going to add groups from yaml {}", yamlName); + + if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) { + groups = validateUpdateVfGroupNamesRes.left().value(); + } else { + groups = parsedToscaYamlInfo.getGroups(); + } + Either createGroupsOnResource = createGroupsOnResource(resource, + csarInfo.getModifier(), groups); + if (createGroupsOnResource.isRight()) { + result = false; + return createGroupsOnResource; + } + resource = createGroupsOnResource.left().value(); + log.trace("************* Finished to add groups from yaml {}", yamlName); + + log.trace("************* Going to add artifacts from yaml {}", yamlName); + + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, + nodeTypesArtifactsToCreate); + + Either createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, + csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + if (createArtifactsEither.isRight()) { + log.debug("failed to update artifacts {}", createArtifactsEither.right().value()); + return createArtifactsEither; + + } + resource = createArtifactsEither.left().value(); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + return Either.left(resource); + + } finally { + if (!inTransaction) { + if (!result) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) { + createdArtifacts.addAll(nodeTypesNewCreatedArtifacts); + log.debug("component and all its artifacts were deleted, id = {}", resource.getName()); + } + + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + if (shouldLock) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + } + + private Either createGroupsOnResource(Resource resource, User user, + Map groups) { + if (groups != null && !groups.isEmpty()) { + Either, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource( + groups, resource); + + if (mergeGroupsUsingResource.isRight()) { + log.debug("Failed to prepare groups for creation"); + return Either.right(mergeGroupsUsingResource.right().value()); + } + List groupsAsList = mergeGroupsUsingResource.left().value(); + Either, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, + groupsAsList); + if (createGroups.isRight()) { + return Either.right(createGroups.right().value()); + } + } else { + return Either.left(resource); + } + Either updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either updateGroupsOnResource(Resource resource, User user, + Map groups) { + if (groups != null && false == groups.isEmpty()) { + List groupsFromResource = resource.getGroups(); + Either, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource( + groups, resource); + + if (mergeGroupsUsingResource.isRight()) { + log.debug("Failed to prepare groups for creation"); + return Either.right(mergeGroupsUsingResource.right().value()); + } + List groupsAsList = mergeGroupsUsingResource.left().value(); + List groupsToUpdate = new ArrayList(); + List groupsToDelete = new ArrayList(); + List groupsToCreate = new ArrayList(); + if (groupsFromResource != null && !groupsFromResource.isEmpty()) { + for (GroupDefinition group : groupsAsList) { + Optional op = groupsFromResource.stream() + .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + if (op.isPresent()) { + GroupDefinition groupToUpdate = op.get(); + groupToUpdate.setMembers(group.getMembers()); + groupsToUpdate.add(groupToUpdate); + } else { + groupsToCreate.add(group); + } + } + for (GroupDefinition group : groupsFromResource) { + Optional op = groupsAsList.stream() + .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny(); + if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) { + + groupsToDelete.add(group); + } + + } + } else + groupsToCreate.addAll(groupsAsList); + Either, ResponseFormat> prepareGroups = null; + if (!groupsToCreate.isEmpty()) { + + if (groupsFromResource != null && !groupsFromResource.isEmpty()) { + prepareGroups = groupBusinessLogic.addGroups(resource, + groupsToCreate); + } else { + prepareGroups = groupBusinessLogic.createGroups(resource, + groupsToCreate); + } + + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + if (!groupsToDelete.isEmpty()) { + prepareGroups = groupBusinessLogic.deleteGroups(resource, + groupsToDelete); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) { + prepareGroups = groupBusinessLogic.updateGroups(resource, groupsToUpdate); + if (prepareGroups.isRight()) { + return Either.right(prepareGroups.right().value()); + } + } + + } else { + return Either.left(resource); + } + + Either updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either createInputsOnResource(Resource resource, User user, + Map inputs, boolean inTransaction) { + List resourceProperties = resource.getInputs(); + if ((inputs != null && false == inputs.isEmpty()) + || (resourceProperties != null && false == resourceProperties.isEmpty())) { + + Either, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, + resource); + if (createInputs.isRight()) { + return Either.right(createInputs.right().value()); + } + } else { + return Either.left(resource); + } + + Either updatedResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (updatedResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(updatedResource.left().value()); + } + + private Either, ResponseFormat> updateGroupMembersUsingResource( + Map groups, Resource component) { + + List result = new ArrayList<>(); + + List componentInstances = component.getComponentInstances(); + + if (groups != null) { + Either validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups); + if (validateCyclicGroupsDependencies.isRight()) { + return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies); + } + for (Entry entry : groups.entrySet()) { + String groupName = entry.getKey(); + + GroupDefinition groupDefinition = entry.getValue(); + + GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition); + updatedGroupDefinition.setMembers(null); + + // get the members of the group + Map members = groupDefinition.getMembers(); + if (members != null) { + Set compInstancesNames = members.keySet(); + + if (componentInstances == null || true == componentInstances.isEmpty()) { + String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); + log.debug( + "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", + membersAstString, groupName, component.getNormalizedName()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component))); + } + // Find all component instances with the member names + Map memberNames = componentInstances.stream() + .collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> ""))); + Map relevantInstances = memberNames.entrySet().stream() + .filter(n -> compInstancesNames.contains(n.getKey())) + .collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue())); + + if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { + + List foundMembers = new ArrayList<>(); + if (relevantInstances != null) { + foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList()); + } + compInstancesNames.removeAll(foundMembers); + String membersAstString = compInstancesNames.stream().collect(Collectors.joining(",")); + log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, + groupName, component.getNormalizedName()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), getComponentTypeForResponse(component))); + } + + updatedGroupDefinition.setMembers(relevantInstances); + } + + result.add(updatedGroupDefinition); + } + } + return Either.left(result); + } + + /** + * This Method validates that there is no cyclic group dependencies. meaning + * group A as member in group B which is member in group A + * + * @param allGroups + * @return + */ + private Either validateCyclicGroupsDependencies(Map allGroups) { + + Either result = Either.left(true); + try { + Iterator> allGroupsItr = allGroups.entrySet().iterator(); + while (allGroupsItr.hasNext() && result.isLeft()) { + Entry groupAEntry = allGroupsItr.next(); + // Fetches a group member A + String groupAName = groupAEntry.getKey(); + // Finds all group members in group A + Set allGroupAMembersNames = new HashSet<>(); + fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames); + // If A is a group member of itself found cyclic dependency + if (allGroupAMembersNames.contains(groupAName)) { + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName); + result = Either.right(responseFormat); + } + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(responseFormat); + log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e); + } + return result; + } + + /** + * This Method fills recursively the set groupMembers with all the members + * of the given group which are also of type group. + * + * @param groupName + * @param allGroups + * @param allGroupMembers + * @return + */ + private void fillAllGroupMemebersRecursivly(String groupName, Map allGroups, + Set allGroupMembers) { + + // Found Cyclic dependency + if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) { + return; + } + GroupDefinition groupDefinition = allGroups.get(groupName); + // All Members Of Current Group Resource Instances & Other Groups + Set currGroupMembers = groupDefinition.getMembers().keySet(); + // Filtered Members Of Current Group containing only members which + // are groups + List currGroupFilteredMembers = currGroupMembers.stream(). + // Keep Only Elements of type group and not Resource Instances + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Add Filtered Elements to main Set + peek(innerGroupName -> allGroupMembers.add(innerGroupName)). + // Collect results + collect(Collectors.toList()); + + // Recursively call the method for all the filtered group members + for (String innerGroupName : currGroupFilteredMembers) { + fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers); + } + + } + + private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map allGroups, + Set allGroupMembers) { + + boolean stop = false; + // In Case Not Group Stop + if (!allGroups.containsKey(groupName)) { + stop = true; + } + // In Case Group Has no members stop + if (!stop) { + GroupDefinition groupDefinition = allGroups.get(groupName); + stop = MapUtils.isEmpty(groupDefinition.getMembers()); + + } + // In Case all group members already contained stop + if (!stop) { + final Set allMembers = allGroups.get(groupName).getMembers().keySet(); + Set membersOfTypeGroup = allMembers.stream(). + // Filter In Only Group members + filter(innerGroupName -> allGroups.containsKey(innerGroupName)). + // Collect + collect(Collectors.toSet()); + stop = allGroupMembers.containsAll(membersOfTypeGroup); + } + return stop; + } + + private Either createRIAndRelationsFromYaml(String yamlName, Resource resource, + Map uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum, + String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + String nodeName) { + + Either result; + Either createResourcesInstancesEither; + + log.debug("************* Going to create all nodes {}", yamlName); + Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, + resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, + nodeTypesInfo, csarInfo, nodeName); + log.debug("************* Finished to create all nodes {}", yamlName); + if (createdResourcesFromdNodeTypeMap.isRight()) { + log.debug("failed to resources from node types status is {}", + createdResourcesFromdNodeTypeMap.right().value()); + return Either.right(createdResourcesFromdNodeTypeMap.right().value()); + } + + log.debug("************* Going to create all resource instances {}", yamlName); + createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, + uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes()); + + log.debug("************* Finished to create all resource instances {}", yamlName); + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = createResourcesInstancesEither; + return createResourcesInstancesEither; + } + resource = createResourcesInstancesEither.left().value(); + log.debug("************* Going to create all relations {}", yamlName); + createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, + uploadComponentInstanceInfoMap); + + log.debug("************* Finished to create all relations {}", yamlName); + + if (createResourcesInstancesEither.isRight()) { + log.debug("failed to create relation between resource instances status is {}", + createResourcesInstancesEither.right().value()); + result = createResourcesInstancesEither; + return result; + } else { + resource = createResourcesInstancesEither.left().value(); + } + + log.debug("************* Going to create positions {}", yamlName); + Either, ResponseFormat> eitherSetPosition = compositionBusinessLogic + .setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId()); + log.debug("************* Finished to set positions {}", yamlName); + result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource); + + return result; + } + + private void handleAndAddExtractedVfcsArtifacts(List vfcArtifacts, + List artifactsToAdd) { + List vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()) + .collect(Collectors.toList()); + artifactsToAdd.stream().forEach(a -> { + if (!vfcArtifactNames.contains(a.getArtifactName())) { + vfcArtifacts.add(a); + } else { + log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName()); + } + }); + + } + + @SuppressWarnings("unchecked") + private Either, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, + String topologyTemplateYaml, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, + CsarInfo csarInfo, String nodeName) { + + Either, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes()); + for (Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { + if (nodeTypeEntry.getValue().isNested()) { + + Either createResourceFromYaml = handleNestedVfc(resource, + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypeEntry.getKey()); + log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); + if (createResourceFromYaml.isRight()) { + return Either.right(createResourceFromYaml.right().value()); + } + } + } + + Map mappedToscaTemplate = null; + if (StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) + && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); + } + if (MapUtils.isEmpty(mappedToscaTemplate)) { + mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); + } + + Either, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList( + yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + if (createdNodeTypeFromMainTemplateEither.isRight()) { + ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value(); + componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + // add the created node types to the cache although they are not in the + // graph. + csarInfo.getCreatedNodes().values().stream() + .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource)); + + return result; + } + + private Either handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, + List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction) { + + if (csarInfo.getCsar() != null) { + String vendorLicenseModelId = null; + String vfLicenseModelId = null; + + if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { + Map deploymentArtifactsMap = resource.getDeploymentArtifacts(); + if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) { + for (Entry artifactEntry : deploymentArtifactsMap.entrySet()) { + if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) + vendorLicenseModelId = artifactEntry.getValue().getUniqueId(); + if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) + vfLicenseModelId = artifactEntry.getValue().getUniqueId(); + } + } + + } + // Specific Behavior for license artifacts + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, + ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, + Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, false, shouldLock, + inTransaction); + createOrUpdateSingleNonMetaArtifact(resource, csarInfo, + CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, + ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, + Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, + artifactOperation, null, false, shouldLock, inTransaction); + + Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, + createdArtifacts, shouldLock, inTransaction, artifactOperation); + if (eitherCreateResult.isRight()) { + return Either.right(eitherCreateResult.right().value()); + } + Either eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + return Either.right(responseFormat); + + } + resource = eitherGerResource.left().value(); + + Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); + + if (artifacsMetaCsarStatus.isLeft()) { + String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); + String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); + Either createArtifactsFromCsar; + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); + else + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); + + if (createArtifactsFromCsar.isRight()) { + log.debug("Couldn't create artifacts from artifacts.meta"); + return Either.right(createArtifactsFromCsar.right().value()); + } + + return Either.left(createArtifactsFromCsar.left().value()); + } else { + + return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction); + + } + } + return Either.left(resource); + } + + + private Either createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, + String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, + String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, + ArtifactOperationInfo operation, List createdArtifacts, boolean isFromCsar, boolean shouldLock, + boolean inTransaction) { + byte[] artifactFileBytes = null; + + if (csarInfo.getCsar().containsKey(artifactPath)) { + artifactFileBytes = csarInfo.getCsar().get(artifactPath); + } + Either result = Either.left(true); + if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) { + if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { + Either, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, + shouldLock, inTransaction); + if (handleDelete.isRight()) { + result = Either.right(handleDelete.right().value()); + } + return result; + } + + + if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { + operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE); + } + + } + if (artifactFileBytes != null) { + Map vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName, + artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, + artifactFileBytes, null, isFromCsar); + Either, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson( + resource, csarInfo.getModifier(), vendorLicenseModelJson, operation); + addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + if (eitherNonMetaArtifacts.isRight()) { + BeEcompErrorManager.getInstance() + .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), + ErrorSeverity.WARNING); + return Either.right(eitherNonMetaArtifacts.right().value()); + } + } + return result; + } + + private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) { + return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar; + } + + + private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, + List createdArtifacts, + Either, ResponseFormat> eitherNonMetaArtifacts) { + if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null + && eitherNonMetaArtifacts.isLeft()) { + Either eitherResult = eitherNonMetaArtifacts.left().value(); + if (eitherResult.isLeft()) { + createdArtifacts.add(eitherResult.left().value()); + } + } + } + + + private Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, + List createdArtifacts, boolean shouldLock, boolean inTransaction, + ArtifactOperationInfo artifactOperation) { + + Either resStatus = null; + Map>> collectedWarningMessages = new HashMap<>(); + + try { + List artifactPathAndNameList = + // Stream of file paths contained in csar + csarInfo.getCsar().entrySet().stream() + // Filter in only VF artifact path location + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) + .matches()) + // Validate and add warnings + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), + collectedWarningMessages)) + // Filter in Non Warnings + .filter(e -> e.isLeft()) + // Convert from Either to NonMetaArtifactInfo + .map(e -> e.left().value()) + // collect to List + .collect(Collectors.toList()); + + Either responseFormatEither = validateArtifactNames(artifactPathAndNameList); + if (responseFormatEither.isRight()) { + return Either.right(getComponentsUtils().getResponseFormatByArtifactId( + ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value())); + } + + EnumMap> vfCsarArtifactsToHandle = null; + + if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { + vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class); + vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList); + } else { + Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( + resource, artifactPathAndNameList, csarInfo.getModifier()); + + if (findVfCsarArtifactsToHandleRes.isRight()) { + resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); + } + if (resStatus == null) { + vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value(); + } + } + + + if (resStatus == null && vfCsarArtifactsToHandle != null) { + + for (Entry> currArtifactOperationPair : vfCsarArtifactsToHandle + .entrySet()) { + + Optional optionalCreateInDBError = + // Stream of artifacts to be created + currArtifactOperationPair.getValue().stream() + // create each artifact + .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), + e.getArtifactName(), e.getArtifactType().getType(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), + CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + currArtifactOperationPair.getKey()), + createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) + // filter in only error + .filter(e -> e.isRight()). + // Convert the error from either to + // ResponseFormat + map(e -> e.right().value()). + // Check if an error occurred + findAny(); + // Error found on artifact Creation + if (optionalCreateInDBError.isPresent()) { + resStatus = Either.right(optionalCreateInDBError.get()); + break; + } + } + } + if (resStatus == null) { + resStatus = Either.left(resource); + } + } catch (Exception e) { + resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e); + } finally { + CsarUtils.handleWarningMessages(collectedWarningMessages); + } + return resStatus; + } + + private Either validateArtifactNames(List artifactPathAndNameList) { + Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); + for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { + if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { + return Either.right(nonMetaArtifactInfo.getArtifactName()); + } + } + return Either.left(true); + } + + private Either>, ResponseFormat> findVfCsarArtifactsToHandle( + Resource resource, List artifactPathAndNameList, User user) { + + List existingArtifacts = new ArrayList<>(); + // collect all Deployment and Informational artifacts of VF + if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getDeploymentArtifacts().values()); + } + if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) { + existingArtifacts.addAll(resource.getArtifacts().values()); + } + existingArtifacts = existingArtifacts.stream() + // filter MANDATORY artifacts, LICENSE artifacts and artifacts + // was created from HEAT.meta + .filter(this::isNonMetaArtifact).collect(Collectors.toList()); + + List artifactsToIgnore = new ArrayList<>(); + // collect IDs of Artifacts of VF which belongs to any group + if (resource.getGroups() != null) { + resource.getGroups().stream().forEach(g -> { + if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) + artifactsToIgnore.addAll(g.getArtifacts()); + }); + } + existingArtifacts = existingArtifacts.stream() + // filter artifacts which belongs to any group + .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList()); + return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user); + } + + private boolean isNonMetaArtifact(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) { + result = false; + } + return result; + } + + private boolean isValidArtifactType(ArtifactDefinition artifact) { + boolean result = true; + if (artifact.getArtifactType() == null + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE + || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) { + result = false; + } + return result; + } + + private Either createResourceInstancesRelations(User user, String yamlName, + Resource resource, Map uploadResInstancesMap) { + log.debug("createResourceInstancesRelations try to create relations "); + List componentInstancesList = resource.getComponentInstances(); + if (uploadResInstancesMap == null) { + log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName); + BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", + yamlName, ErrorSeverity.ERROR); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return Either.right(responseFormat); + } + + if (componentInstancesList == null || componentInstancesList.isEmpty()) { + log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return Either.right(responseFormat); + } + + log.debug("Before validateAndUpdatePropertyValue"); + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", + "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName)); + + } + + Map> instProperties = new HashMap<>(); + Map>> instCapabilties = new HashMap<>(); + Map>> instRequirements = new HashMap<>(); + Map> instDeploymentArtifacts = new HashMap<>(); + Map> instArtifacts = new HashMap<>(); + Map> instAttributes = new HashMap<>(); + Map originCompMap = new HashMap<>(); + List relations = new ArrayList<>(); + + Map> instInputs = new HashMap<>(); + + for (Entry entry : uploadResInstancesMap.entrySet()) { + log.trace("Processing entry: {}", entry); + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + log.trace("Processing component instance: {}", compInstance); + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return Either.right(responseFormat); + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + Resource originResource; + if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { + Either getOriginResourceRes = toscaOperationFacade + .getToscaFullElement(currentCompInstance.getComponentUid()); + if (getOriginResourceRes.isRight()) { + log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", + currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), + getOriginResourceRes); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); + return Either.right(responseFormat); + } + originResource = getOriginResourceRes.left().value(); + originCompMap.put(originResource.getUniqueId(), originResource); + } else { + originResource = originCompMap.get(currentCompInstance.getComponentUid()); + } + if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) + instRequirements.put(currentCompInstance, originResource.getRequirements()); + if (MapUtils.isNotEmpty(originResource.getCapabilities())) { + Map> originCapabilities; + if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { + originCapabilities = new HashMap<>(); + originResource.getCapabilities().entrySet().stream().forEach(e -> { + List list = e.getValue().stream().map(l -> new CapabilityDefinition(l)) + .collect(Collectors.toList()); + originCapabilities.put(e.getKey(), list); + }); + Map> newPropertiesMap = new HashMap<>(); + for (List capabilities : uploadComponentInstanceInfo.getCapabilities().values()) { + for (UploadCapInfo capability : capabilities) { + if (CollectionUtils.isNotEmpty(capability.getProperties())) { + newPropertiesMap.put(capability.getName(), capability.getProperties().stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p))); + } + } + } + for (List capabilities : originCapabilities.values()) { + List filteredCapabilities = capabilities.stream() + .filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList()); + for (CapabilityDefinition cap : filteredCapabilities) { + Either updateRes = updatePropertyValues(cap.getProperties(), + newPropertiesMap.get(cap.getName()), allDataTypes.left().value()); + if (updateRes.isRight()) { + log.debug("Failed to update capability properties of capability {} . Status is {}. ", + cap.getName(), updateRes.right().value()); + return Either.right(updateRes.right().value()); + } + } + } + } else { + originCapabilities = originResource.getCapabilities(); + } + instCapabilties.put(currentCompInstance, originCapabilities); + } + if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) + instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); + if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) + instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); + if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) + instAttributes.put(resourceInstanceId, originResource.getAttributes()); + if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { + ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, + originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value()); + if (addPropertiesValueToRiRes.getStatus() != 200) { + return Either.right(addPropertiesValueToRiRes); + } + } else { + ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, + originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value()); + if (addInputValueToRiRes.getStatus() != 200) { + return Either.right(addInputValueToRiRes); + } + } + } + + Either>, StorageOperationStatus> addPropToInst = toscaOperationFacade + .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId()); + if (addPropToInst.isRight()) { + log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), + addPropToInst.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName); + return Either.right(responseFormat); + } + if (instInputs != null && !instInputs.isEmpty()) { + Either>, StorageOperationStatus> addInputToInst = toscaOperationFacade + .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId()); + if (addInputToInst.isRight()) { + log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), + addInputToInst.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName); + return Either.right(responseFormat); + } + } + StorageOperationStatus addArtToInst = toscaOperationFacade + .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, + resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, + resource.getUniqueId()); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreComponentInstancesProperties(false); + parametersView.setIgnoreCapabilities(false); + parametersView.setIgnoreRequirements(false); + + Either eitherGetResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + + return Either.right(responseFormat); + + } + + resource = eitherGetResource.left().value(); + + for (Entry entry : uploadResInstancesMap.entrySet()) { + UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); + ComponentInstance currentCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return Either.right(responseFormat); + } + + ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations); + if (addRelationToRiRes.getStatus() != 200) { + return Either.right(addRelationToRiRes); + } + } + + addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations); + if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { + log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), + addArtToInst); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + return Either.right(responseFormat); + } + + if (resource.getResourceType() == ResourceTypeEnum.CVFC) { + eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(), + uploadResInstancesMap); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + } + + log.debug("************* in create relations, getResource start"); + eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); + log.debug("************* in create relations, getResource end"); + if (eitherGetResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + return Either.right(responseFormat); + } + return Either.left(eitherGetResource.left().value()); + } + + private Either updatePropertyValues(List properties, + Map newProperties, Map allDataTypes) { + for (ComponentInstanceProperty property : properties) { + Either updateRes = updatePropertyValue(property, + newProperties.get(property.getName()), allDataTypes); + if (updateRes.isRight()) { + log.debug("Failed to update capability property {} . Status is {}. ", property.getName(), + updateRes.right().value()); + return Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value()))); + } + } + return Either.left(true); + } + + private Either updatePropertyValue(ComponentInstanceProperty property, + UploadPropInfo propertyInfo, Map allDataTypes) { + String value = null; + List getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + property.setValue(value); + return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes); + } + + private Either updateCalculatedCapReqWithSubstitutionMappings(Resource resource, + Map uploadResInstancesMap) { + Either updateRes = null; + Map>> updatedInstCapabilities = new HashMap<>(); + Map>> updatedInstRequirements = new HashMap<>(); + StorageOperationStatus status = toscaOperationFacade + .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + if (updateRes == null) { + fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, + updatedInstCapabilities, updatedInstRequirements); + status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, + resource.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + log.debug( + "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", + resource.getUniqueId(), status); + updateRes = Either.right(status); + } + } + if (updateRes == null) { + updateRes = Either.left(resource); + } + return updateRes; + } + + private void fillUpdatedInstCapabilitiesRequirements(List componentInstances, + Map uploadResInstancesMap, + Map>> updatedInstCapabilities, + Map>> updatedInstRequirements) { + + componentInstances.stream().forEach(i -> { + fillUpdatedInstCapabilities(updatedInstCapabilities, i, + uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); + fillUpdatedInstRequirements(updatedInstRequirements, i, + uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); + }); + } + + private void fillUpdatedInstRequirements( + Map>> updatedInstRequirements, + ComponentInstance instance, Map requirementsNamesToUpdate) { + Map> updatedRequirements = new HashMap<>(); + Set updatedReqNames = new HashSet<>(); + if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) { + for (Map.Entry> requirements : instance.getRequirements().entrySet()) { + updatedRequirements.put(requirements.getKey(), + requirements.getValue().stream() + .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) + && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) + .map(r -> { + r.setParentName(r.getName()); + r.setName(requirementsNamesToUpdate.get(r.getName())); + updatedReqNames.add(r.getName()); + return r; + }).collect(Collectors.toList())); + } + } + if (MapUtils.isNotEmpty(updatedRequirements)) { + updatedInstRequirements.put(instance, updatedRequirements); + } + } + + private void fillUpdatedInstCapabilities( + Map>> updatedInstCapabilties, + ComponentInstance instance, Map capabilitiesNamesToUpdate) { + Map> updatedCapabilities = new HashMap<>(); + Set updatedCapNames = new HashSet<>(); + if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) { + for (Map.Entry> requirements : instance.getCapabilities().entrySet()) { + updatedCapabilities.put(requirements.getKey(), + requirements.getValue().stream() + .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) + && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) + .map(c -> { + c.setParentName(c.getName()); + c.setName(capabilitiesNamesToUpdate.get(c.getName())); + updatedCapNames.add(c.getName()); + return c; + }).collect(Collectors.toList())); + } + } + if (MapUtils.isNotEmpty(updatedCapabilities)) { + updatedInstCapabilties.put(instance, updatedCapabilities); + } + } + + private ResponseFormat addRelationToRI(String yamlName, Resource resource, + UploadComponentInstanceInfo nodesInfoValue, List relations) { + List componentInstancesList = resource.getComponentInstances(); + + UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue; + + ComponentInstance currentCompInstance = null; + + for (ComponentInstance compInstance : componentInstancesList) { + + if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) { + currentCompInstance = compInstance; + break; + } + + } + + if (currentCompInstance == null) { + log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), + resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlName); + return responseFormat; + } + String resourceInstanceId = currentCompInstance.getUniqueId(); + + Map> regMap = uploadComponentInstanceInfo.getRequirements(); + + if (regMap != null) { + Iterator>> nodesRegValue = regMap.entrySet().iterator(); + + while (nodesRegValue.hasNext()) { + Entry> nodesRegInfoEntry = nodesRegValue.next(); + + List uploadRegInfoList = nodesRegInfoEntry.getValue(); + for (UploadReqInfo uploadRegInfo : uploadRegInfoList) { + log.debug("Going to create relation {}", uploadRegInfo.getName()); + String regName = uploadRegInfo.getName(); + RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef(); + regCapRelDef.setFromNode(resourceInstanceId); + log.debug("try to find available requirement {} ", regName); + Either eitherReqStatus = findAviableRequiremen(regName, + yamlName, uploadComponentInstanceInfo, currentCompInstance, + uploadRegInfo.getCapabilityName()); + if (eitherReqStatus.isRight()) { + log.debug("failed to find available requirement {} status is {}", regName, + eitherReqStatus.right().value()); + return eitherReqStatus.right().value(); + } + + RequirementDefinition validReq = eitherReqStatus.left().value(); + List reqAndRelationshipPairList = regCapRelDef + .getRelationships(); + if (reqAndRelationshipPairList == null) + reqAndRelationshipPairList = new ArrayList<>(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + reqAndRelationshipPair.setRequirement(regName); + reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId()); + reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId()); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(validReq.getCapability()); + reqAndRelationshipPair.setRelationships(relationship); + + ComponentInstance currentCapCompInstance = null; + for (ComponentInstance compInstance : componentInstancesList) { + if (compInstance.getName().equals(uploadRegInfo.getNode())) { + currentCapCompInstance = compInstance; + break; + } + } + + if (currentCapCompInstance == null) { + log.debug("The component instance with name {} not found on resource {} ", + uploadRegInfo.getNode(), resource.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "component instance with name " + uploadRegInfo.getNode() + " in resource {} ", + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); + log.debug("try to find aviable Capability req name is {} ", validReq.getName()); + CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, + currentCapCompInstance, uploadRegInfo); + if (aviableCapForRel == null) { + log.debug("aviable capability was not found. req name is {} component instance is {}", + validReq.getName(), currentCapCompInstance.getUniqueId()); + BeEcompErrorManager.getInstance().logInternalDataError( + "aviable capability was not found. req name is " + validReq.getName() + + " component instance is " + currentCapCompInstance.getUniqueId(), + resource.getUniqueId(), ErrorSeverity.ERROR); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + return responseFormat; + } + reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); + reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); + reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(reqAndRelationshipPair); + reqAndRelationshipPairList.add(capReqRel); + regCapRelDef.setRelationships(reqAndRelationshipPairList); + relations.add(regCapRelDef); + } + } + } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName); + return responseFormat; + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, + Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, + Map> instInputs, Map allDataTypes) { + Map> propMap = uploadComponentInstanceInfo.getProperties(); + if (propMap != null && propMap.size() > 0) { + Map currPropertiesMap = new HashMap(); + + List listFromMap = originResource.getInputs(); + if (listFromMap == null || listFromMap.isEmpty()) { + log.debug("failed to find properties "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + return responseFormat; + } + for (InputDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + List instPropList = new ArrayList<>(); + for (List propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + propName); + return responseFormat; + } + InputDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceInput property = null; + + String value = null; + List getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + curPropertyDef.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + String innerType = null; + property = new ComponentInstanceInput(curPropertyDef, value, null); + + Either validatevalueEiter = validatePropValueBeforeCreate(property, + value, isValidate, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + return componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); + } + + property.setValue(validatevalueEiter.left().value()); + + if (getInputs != null && !getInputs.isEmpty()) { + List getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", + property, currentCompInstance.getUniqueId()); + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + + Optional optional = inputs.stream() + .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) + .findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInputIndex.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + } + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (InputDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceInput(value)); + } + } + instInputs.put(currentCompInstance.getUniqueId(), instPropList); + } + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, + Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName, + Map> instProperties, Map allDataTypes) { + + Map> propMap = uploadComponentInstanceInfo.getProperties(); + Map currPropertiesMap = new HashMap(); + + List listFromMap = originResource.getProperties(); + if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) { + log.debug("failed to find properties "); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND); + return responseFormat; + } + if (listFromMap == null || listFromMap.isEmpty()) { + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + for (PropertyDefinition prop : listFromMap) { + String propName = prop.getName(); + if (!currPropertiesMap.containsKey(propName)) { + currPropertiesMap.put(propName, prop); + } + } + List instPropList = new ArrayList<>(); + if (propMap != null && propMap.size() > 0) { + for (List propertyList : propMap.values()) { + + UploadPropInfo propertyInfo = propertyList.get(0); + String propName = propertyInfo.getName(); + if (!currPropertiesMap.containsKey(propName)) { + log.debug("failed to find property {} ", propName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, + propName); + return responseFormat; + } + PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); + ComponentInstanceProperty property = null; + + String value = null; + List getInputs = null; + boolean isValidate = true; + if (propertyInfo.getValue() != null) { + getInputs = propertyInfo.getGet_input(); + isValidate = getInputs == null || getInputs.isEmpty(); + if (isValidate) { + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + curPropertyDef.getType()); + } else + value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), + ToscaTagNamesEnum.GET_INPUT.getElementName()); + } + String innerType = null; + property = new ComponentInstanceProperty(curPropertyDef, value, null); + + Either validatevalueEiter = validatePropValueBeforeCreate(property, + value, isValidate, innerType, allDataTypes); + if (validatevalueEiter.isRight()) { + return componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value())); + } + + property.setValue(validatevalueEiter.left().value()); + + if (getInputs != null && !getInputs.isEmpty()) { + List getInputValues = new ArrayList<>(); + for (GetInputValueDataDefinition getInput : getInputs) { + List inputs = resource.getInputs(); + if (inputs == null || inputs.isEmpty()) { + log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", + property, currentCompInstance.getUniqueId()); + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + + Optional optional = inputs.stream() + .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInput.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition input = optional.get(); + getInput.setInputId(input.getUniqueId()); + getInputValues.add(getInput); + + GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex(); + if (getInputIndex != null) { + optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) + .findAny(); + if (!optional.isPresent()) { + log.debug("Failed to find input {} ", getInputIndex.getInputName()); + // @@TODO error message + return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + } + InputDefinition inputIndex = optional.get(); + getInputIndex.setInputId(inputIndex.getUniqueId()); + getInputValues.add(getInputIndex); + + } + + } + property.setGetInputValues(getInputValues); + } + instPropList.add(property); + // delete overriden property + currPropertiesMap.remove(property.getName()); + } + } + // add rest of properties + if (!currPropertiesMap.isEmpty()) { + for (PropertyDefinition value : currPropertiesMap.values()) { + instPropList.add(new ComponentInstanceProperty(value)); + } + } + instProperties.put(currentCompInstance.getUniqueId(), instPropList); + return componentsUtils.getResponseFormat(ActionStatus.OK); + } + + // US740820 Relate RIs according to capability name + private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + if (null == uploadReqInfo.getCapabilityName() + || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get + // by + // capability + // type + return findAviableCapability(validReq, currentCapCompInstance); + } + return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo); + } + + private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) { + CapabilityDefinition cap = null; + Map> capMap = currentCapCompInstance.getCapabilities(); + if (!capMap.containsKey(validReq.getCapability())) { + return null; + } + Optional capByName = capMap.get(validReq.getCapability()).stream() + .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny(); + if (!capByName.isPresent()) { + return null; + } + cap = capByName.get(); + + if (cap.getMaxOccurrences() != null + && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + + } + + } + return cap; + } + + private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, + ComponentInstance currentCapCompInstance) { + CapabilityDefinition aviableCapForRel = null; + Map> capMap = currentCapCompInstance.getCapabilities(); + if (capMap.containsKey(validReq.getCapability())) { + List capList = capMap.get(validReq.getCapability()); + + for (CapabilityDefinition cap : capList) { + if (cap.getMaxOccurrences() != null + && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = cap.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + cap.setLeftOccurrences(String.valueOf(left)); + aviableCapForRel = cap; + break; + } else { + continue; + } + } else { + aviableCapForRel = cap; + break; + } + } + } + return aviableCapForRel; + } + + private Either findAviableRequiremen(String regName, String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, + String capName) { + Map> comInstRegDefMap = currentCompInstance.getRequirements(); + List list = comInstRegDefMap.get(capName); + RequirementDefinition validRegDef = null; + if (list == null) { + for (Entry> entry : comInstRegDefMap.entrySet()) { + for (RequirementDefinition reqDef : entry.getValue()) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null + && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + + } + } + if (validRegDef != null) { + break; + } + } + } else { + for (RequirementDefinition reqDef : list) { + if (reqDef.getName().equals(regName)) { + if (reqDef.getMaxOccurrences() != null + && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + String leftOccurrences = reqDef.getLeftOccurrences(); + if (leftOccurrences == null) { + leftOccurrences = reqDef.getMaxOccurrences(); + } + int left = Integer.parseInt(leftOccurrences); + if (left > 0) { + --left; + reqDef.setLeftOccurrences(String.valueOf(left)); + validRegDef = reqDef; + break; + } else { + continue; + } + } else { + validRegDef = reqDef; + break; + } + } + } + } + if (validRegDef == null) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + return Either.left(validRegDef); + } + + @SuppressWarnings("unchecked") + public Either parseResourceInfoFromYaml(String yamlFileName, Resource resource, + String resourceYml, Map createdNodesToscaResourceNames, + Map nodeTypesInfo, String nodeName) { + + Map mappedToscaTemplate; + if (nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)) { + mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); + } else { + try { + // DE154502 Fail if duplicate key found in file + mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml); + + } catch (ParserException e) { + log.error("Failed to load yaml file {}", yamlFileName, e); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, + yamlFileName, e.getMessage()); + return Either.right(responseFormat); + } + } + Either toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, + ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); + if (toscaElementEither.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + return Either.right(responseFormat); + } + + Either, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, + mappedToscaTemplate, resource); + if (createInputsEither.isRight()) { + ResponseFormat responseFormat = createInputsEither.right().value(); + return Either.right(responseFormat); + } + + Either, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml( + yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames); + if (uploadResInstancesEither.isRight()) { + ResponseFormat responseFormat = uploadResInstancesEither.right().value(); + return Either.right(responseFormat); + } + + Either, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, + mappedToscaTemplate, resource); + if (createGroupsFromYaml.isRight()) { + ResponseFormat responseFormat = createGroupsFromYaml.right().value(); + return Either.right(responseFormat); + } + + ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo(); + parsedToscaYamlInfo.setInputs(createInputsEither.left().value()); + parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value()); + parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value()); + + return Either.left(parsedToscaYamlInfo); + } + + private Either createResourceInstances(User user, String yamlName, Resource resource, + Map uploadResInstancesMap, boolean inTransaction, boolean needLock, + Map nodeNamespaceMap) { + + Either eitherResource = null; + log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); + if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + + return Either.right(responseFormat); + + } + Map existingnodeTypeMap = new HashMap<>(); + if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) { + nodeNamespaceMap.entrySet().stream() + .forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue())); + } + + Iterator> nodesInfoValue = uploadResInstancesMap.entrySet() + .iterator(); + Map resourcesInstancesMap = new HashMap<>(); + while (nodesInfoValue.hasNext()) { + log.debug("*************Going to create resource instances {}", yamlName); + Entry uploadComponentInstanceInfoEntry = nodesInfoValue.next(); + UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue(); + + // updating type if the type is node type name - we need to take the + // updated name + log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + uploadComponentInstanceInfo + .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); + } + + eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, + existingnodeTypeMap); + if (eitherResource.isRight()) { + return eitherResource; + } + Resource refResource = eitherResource.left().value(); + + ComponentInstance componentInstance = new ComponentInstance(); + + componentInstance.setComponentUid(refResource.getUniqueId()); + + ComponentTypeEnum containerComponentType = resource.getComponentType(); + NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); + + if (containerNodeType.equals(NodeTypeEnum.Resource) + && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) + && MapUtils.isNotEmpty(refResource.getCapabilities())) { + setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); + Either>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities( + refResource.getUniqueId(), refResource.getCapabilities(), + uploadComponentInstanceInfo.getCapabilities()); + if (getValidComponentInstanceCapabilitiesRes.isRight()) { + return Either.right(getValidComponentInstanceCapabilitiesRes.right().value()); + } else { + componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value()); + } + } + if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { + log.debug( + "createResourceInstances - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); + componentInstance.setName(uploadComponentInstanceInfo.getName()); + componentInstance.setIcon(origResource.getIcon()); + + resourcesInstancesMap.put(componentInstance, origResource); + + } + if (MapUtils.isNotEmpty(resourcesInstancesMap)) { + + StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, + resourcesInstancesMap, false); + if (status != null && status != StorageOperationStatus.OK) { + log.debug("Failed to add component instances to container component {}", resource.getName()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(status)); + eitherResource = Either.right(responseFormat); + return eitherResource; + } + + } + + log.debug("*************Going to get resource {}", resource.getUniqueId()); + ComponentParametersView parametersView = new ComponentParametersView(); + parametersView.disableAll(); + parametersView.setIgnoreComponentInstances(false); + parametersView.setIgnoreUsers(false); + parametersView.setIgnoreInputs(false); // inputs are read when creating + // property values on instances + Either eitherGerResource = toscaOperationFacade + .getToscaElement(resource.getUniqueId(), parametersView); + log.debug("*************finished to get resource {}", resource.getUniqueId()); + if (eitherGerResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + + return Either.right(responseFormat); + + } + + if (eitherGerResource.left().value().getComponentInstances() == null + || eitherGerResource.left().value().getComponentInstances().isEmpty()) { + + log.debug("Error when create resource inctanse from csar. ComponentInstances list empty"); + BeEcompErrorManager.getInstance().logBeDaoSystemError( + "Error when create resource inctanse from csar. ComponentInstances list empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE); + return Either.right(responseFormat); + + } + + return Either.left(eitherGerResource.left().value()); + } + + private void setCapabilityNamesTypes(Map> originCapabilities, + Map> uploadedCapabilities) { + for (Entry> currEntry : uploadedCapabilities.entrySet()) { + if (originCapabilities.containsKey(currEntry.getKey())) { + currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey())); + } + } + for (Map.Entry> capabilities : originCapabilities.entrySet()) { + capabilities.getValue().stream().forEach(cap -> { + if (uploadedCapabilities.containsKey(cap.getName())) { + uploadedCapabilities.get(cap.getName()).stream().forEach(c -> { + c.setName(cap.getName()); + c.setType(cap.getType()); + }); + } + ; + }); + } + + } + + private Either validateResourceInstanceBeforeCreate(String yamlName, + UploadComponentInstanceInfo uploadComponentInstanceInfo, Map nodeNamespaceMap) { + log.debug( + "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + Resource refResource = null; + if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { + refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); + } else { + Either findResourceEither = toscaOperationFacade + .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType()); + if (findResourceEither.isRight()) { + log.debug( + "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", + uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + return Either.right(responseFormat); + } + refResource = findResourceEither.left().value(); + nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource); + } + String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); + if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + log.debug( + "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", + refResource.getName(), componentState); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, + refResource.getComponentType().getValue(), refResource.getName(), componentState); + return Either.right(responseFormat); + } + + if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) { + log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + return Either.right(responseFormat); + } + return Either.left(refResource); + } + + private Either, ResponseFormat> createResourcesInstanceInfoFromYaml( + String yamlFileName, Map toscaJson, Resource resource, + Map createdNodesToscaResourceNames) { + Map moduleComponentInstances = new HashMap(); + Map substitutionMappings = null; + Either, ResponseFormat> result = Either.left(moduleComponentInstances); + Either, ResultStatusEnum> eitherNodesTemlates = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES); + Either, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS); + if (eitherSubstitutionMappings.isLeft()) { + substitutionMappings = eitherSubstitutionMappings.left().value(); + } + if (eitherNodesTemlates.isLeft()) { + Map jsonNodeTemplates = eitherNodesTemlates.left().value(); + + Iterator> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry nodeNameValue = nodesNameValue.next(); + Either eitherNode = createModuleComponentInstanceInfo( + nodeNameValue, substitutionMappings, createdNodesToscaResourceNames); + if (eitherNode.isRight()) { + log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), + resource.getName()); + return Either.right(eitherNode.right().value()); + } else { + UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value(); + moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo); + } + + } + + } + if (moduleComponentInstances.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, + yamlFileName); + return Either.right(responseFormat); + } + + return result; + } + + @SuppressWarnings("unchecked") + private Either createModuleComponentInstanceInfo( + Entry nodeTemplateJsonEntry, Map substitutionMappings, + Map createdNodesToscaResourceNames) { + + UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo(); + Either result = Either.left(nodeTemplateInfo); + nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey()); + try { + if (nodeTemplateJsonEntry.getValue() instanceof String) { + String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue(); + nodeTemplateInfo.setType(nodeTemplateJsonString); + } else if (nodeTemplateJsonEntry.getValue() instanceof Map) { + Map nodeTemplateJsonMap = (Map) nodeTemplateJsonEntry.getValue(); + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String toscaResourceType = (String) nodeTemplateJsonMap + .get(ToscaTagNamesEnum.TYPE.getElementName()); + if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) { + toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType); + } + nodeTemplateInfo.setType(toscaResourceType); + } + + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { + Either>, ResponseFormat> regResponse = createReqModuleFromYaml( + nodeTemplateInfo, nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + nodeTemplateInfo.setRequirements(regResponse.left().value()); + } + } + + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { + Either>, ResponseFormat> eitherCapRes = createCapModuleFromYaml( + nodeTemplateInfo, nodeTemplateJsonMap); + if (eitherCapRes.isRight()) + return Either.right(eitherCapRes.right().value()); + if (eitherCapRes.left().value().size() > 0) { + nodeTemplateInfo.setCapabilities(eitherCapRes.left().value()); + } + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Either>, ResponseFormat> regResponse = createPropModuleFromYaml( + nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + nodeTemplateInfo.setProperties(regResponse.left().value()); + } + } + if (substitutionMappings != null) { + if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) { + Either, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate( + nodeTemplateInfo, (Map>) substitutionMappings + .get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); + if (getCapNamesToUpdateRes.isRight()) + return Either.right(getCapNamesToUpdateRes.right().value()); + if (getCapNamesToUpdateRes.left().value().size() > 0) { + nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value()); + } + } + if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) { + Either, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate( + nodeTemplateInfo, (Map>) substitutionMappings + .get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); + if (getReqNamesToUpdateRes.isRight()) + return Either.right(getReqNamesToUpdateRes.right().value()); + if (getReqNamesToUpdateRes.left().value().size() > 0) { + nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value()); + } + } + } + } else { + + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); + log.debug("error when creating capability, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private Either, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, + Map> elements) { + Either, ResponseFormat> response; + try { + Map namesToUpdate = elements.entrySet().stream() + .filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())) + .collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey())); + response = Either.left(namesToUpdate); + } catch (Exception e) { + log.debug("The exception occurred upon adding names to update for instance {}: ", nodeTemplateInfo.getName(), e); + response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return response; + } + + @SuppressWarnings("unchecked") + private Either>, ResponseFormat> createPropModuleFromYaml( + Map nodeTemplateJsonMap) { + Map> moduleProp = new HashMap>(); + Either>, ResponseFormat> response = Either.left(moduleProp); + Either, ResultStatusEnum> toscaProperties = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES); + if (toscaProperties.isLeft()) { + Map jsonProperties = toscaProperties.left().value(); + for (Entry jsonPropObj : jsonProperties.entrySet()) { + // Property + String propName = jsonPropObj.getKey(); + Object propValue = jsonPropObj.getValue(); + + if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(TOKEN_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(CONCAT_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + if (valueContainsPattern(GET_ATTRIBUTE_PATTERN, propValue)) { + log.trace("Ignore property value {}.", propName); + continue; + } + + UploadPropInfo propertyDef = new UploadPropInfo(); + propertyDef.setValue(propValue); + propertyDef.setName(propName); + if (propValue instanceof Map) { + if (((Map) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + propertyDef.setType(((Map) propValue) + .get(ToscaTagNamesEnum.TYPE.getElementName()).toString()); + } + + if (((Map) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()) + || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()) + .contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + createGetInputModuleFromMap(propName, (Map) propValue, propertyDef); + } + + if (((Map) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + propertyDef.setDescription(((Map) propValue) + .get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString()); + } + if (((Map) propValue) + .containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) { + propertyDef.setValue(((Map) propValue) + .get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())); + } + if (((Map) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) { + propertyDef.setPassword(Boolean.getBoolean(((Map) propValue) + .get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString())); + } else { + propertyDef.setValue(propValue); + } + } else if (propValue instanceof List) { + List propValueList = (List) propValue; + + createInputPropList(propertyDef, propValueList); + propertyDef.setValue(propValue); + } + + if (moduleProp.containsKey(propName)) { + moduleProp.get(propName).add(propertyDef); + } else { + List list = new ArrayList(); + list.add(propertyDef); + moduleProp.put(propName, list); + } + } + } + return response; + } + + @SuppressWarnings("unchecked") + private void createInputPropList(UploadPropInfo propertyDef, List propValueList) { + for (Object objValue : propValueList) { + + if (objValue instanceof Map) { + Map objMap = (Map) objValue; + if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) + createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef); + else { + Set keys = objMap.keySet(); + for (String key : keys) { + Object value = objMap.get(key); + if (value instanceof Map) { + createGetInputModuleFromMap(key, (Map) value, propertyDef); + + } else if (value instanceof List) { + List propSubValueList = (List) value; + + createInputPropList(propertyDef, propSubValueList); + } + + } + } + + } else if (objValue instanceof List) { + List propSubValueList = (List) objValue; + + createInputPropList(propertyDef, propSubValueList); + + } + + } + } + + @SuppressWarnings("unchecked") + private void createGetInputModuleFromMap(String propName, Map propValue, + UploadPropInfo propertyDef) { + + if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName()); + GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition(); + List getInputs = propertyDef.getGet_input(); + if (getInputs == null) { + getInputs = new ArrayList(); + } + if (getInput instanceof String) { + + getInputInfo.setInputName((String) getInput); + getInputInfo.setPropName(propName); + + } else if (getInput instanceof List) { + List getInputList = (List) getInput; + getInputInfo.setPropName(propName); + getInputInfo.setInputName((String) getInputList.get(0)); + if (getInputList.size() > 1) { + Object indexObj = getInputList.get(1); + if (indexObj instanceof Integer) { + getInputInfo.setIndexValue((Integer) indexObj); + } else if (indexObj instanceof Float) { + int index = ((Float) indexObj).intValue(); + getInputInfo.setIndexValue(index); + } else if (indexObj instanceof Map && ((Map) indexObj) + .containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) { + Object index = ((Map) indexObj) + .get(ToscaTagNamesEnum.GET_INPUT.getElementName()); + GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition(); + getInputInfoIndex.setInputName((String) index); + getInputInfoIndex.setPropName(propName); + getInputInfo.setGetInputIndex(getInputInfoIndex); + } + getInputInfo.setList(true); + } + + } + getInputs.add(getInputInfo); + propertyDef.setGet_input(getInputs); + propertyDef.setValue(propValue); + } else { + Set keys = propValue.keySet(); + for (String key : keys) { + Object value = propValue.get(key); + if (value instanceof Map) { + createGetInputModuleFromMap(key, (Map) value, propertyDef); + + } else if (value instanceof List) { + List valueList = (List) value; + for (Object o : valueList) { + if (o instanceof Map) { + createGetInputModuleFromMap(key, (Map) o, propertyDef); + + } + } + + } + + } + + } + } + + + private boolean valueContainsPattern(Pattern pattern, Object propValue) { + + log.debug("valueContainsToken value is {}", propValue); + boolean result = false; + if (propValue != null) { + log.trace("valueContainspattern value is {}", propValue.getClass()); + Matcher matcher = pattern.matcher(propValue.toString()); + result = matcher.find(); + } + + return result; + + } + + @SuppressWarnings("unchecked") + private Either>, ResponseFormat> createReqModuleFromYaml( + UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { + Map> moduleRequirements = new HashMap>(); + Either>, ResponseFormat> response = Either.left(moduleRequirements); + Either, ResultStatusEnum> requirementsListRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); + + if (requirementsListRes.isLeft()) { + for (Object jsonReqObj : requirementsListRes.left().value()) { + String reqName = ((Map) jsonReqObj).keySet().iterator().next(); + Object reqJson = ((Map) jsonReqObj).get(reqName); + Either eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, + moduleRequirements, reqJson, reqName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } else { + Either, ResultStatusEnum> requirementsMapRes = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS); + if (requirementsMapRes.isLeft()) { + for (Map.Entry entry : requirementsMapRes.left().value().entrySet()) { + String reqName = entry.getKey(); + Object reqJson = entry.getValue(); + Either eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, + moduleRequirements, reqJson, reqName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } + } + return response; + } + + private Either addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo, + Map> moduleRequirements, Object requirementJson, String requirementName) { + + Either eitherRequirement = createModuleNodeTemplateReg(requirementJson); + if (eitherRequirement.isRight()) { + log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo); + return Either.right(eitherRequirement.right().value()); + } else { + UploadReqInfo requirementDef = eitherRequirement.left().value(); + requirementDef.setName(requirementName); + if (moduleRequirements.containsKey(requirementName)) { + moduleRequirements.get(requirementName).add(requirementDef); + } else { + List list = new ArrayList(); + list.add(requirementDef); + moduleRequirements.put(requirementName, list); + } + } + return Either.left(eitherRequirement.left().value()); + } + + @SuppressWarnings("unchecked") + private Either>, ResponseFormat> createCapModuleFromYaml( + UploadComponentInstanceInfo nodeTemplateInfo, Map nodeTemplateJsonMap) { + Map> moduleCap = new HashMap<>(); + Either>, ResponseFormat> response = Either.left(moduleCap); + Either, ResultStatusEnum> capabilitiesListRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); + if (capabilitiesListRes.isLeft()) { + for (Object jsonCapObj : capabilitiesListRes.left().value()) { + String key = ((Map) jsonCapObj).keySet().iterator().next(); + Object capJson = ((Map) jsonCapObj).get(key); + Either eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, + capJson, key); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } else { + Either, ResultStatusEnum> capabilitiesMapRes = ImportUtils + .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES); + if (capabilitiesMapRes.isLeft()) { + for (Map.Entry entry : capabilitiesMapRes.left().value().entrySet()) { + String capName = entry.getKey(); + Object capJson = entry.getValue(); + Either eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, + moduleCap, capJson, capName); + if (eitherCap.isRight()) { + return Either.right(eitherCap.right().value()); + } + } + } + } + return response; + } + + private Either addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, + Map> moduleCap, Object capJson, String key) { + + Either eitherCap = createModuleNodeTemplateCap(capJson); + if (eitherCap.isRight()) { + log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo); + return Either.right(eitherCap.right().value()); + } else { + UploadCapInfo capabilityDef = eitherCap.left().value(); + capabilityDef.setKey(key); + if (moduleCap.containsKey(key)) { + moduleCap.get(key).add(capabilityDef); + } else { + List list = new ArrayList(); + list.add(capabilityDef); + moduleCap.put(key, list); + } + } + return Either.left(eitherCap.left().value()); + } + + @SuppressWarnings("unchecked") + private Either createModuleNodeTemplateCap(Object capObject) { + UploadCapInfo capTemplateInfo = new UploadCapInfo(); + Either result = Either.left(capTemplateInfo); + + if (capObject instanceof String) { + String nodeTemplateJsonString = (String) capObject; + capTemplateInfo.setNode(nodeTemplateJsonString); + } else if (capObject instanceof Map) { + Map nodeTemplateJsonMap = (Map) capObject; + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { + Either, ResultStatusEnum> validSourceTypesRes = ImportUtils + .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES); + if (validSourceTypesRes.isLeft()) { + capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream() + .map(o -> o.toString()).collect(Collectors.toList())); + } + } + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Either>, ResponseFormat> regResponse = createPropModuleFromYaml( + nodeTemplateJsonMap); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (!regResponse.left().value().isEmpty()) { + List properties = new ArrayList(); + regResponse.left().value().values().forEach(list -> properties.addAll(list)); + if (!properties.isEmpty()) + capTemplateInfo.setProperties(properties); + } + } + } + return result; + } + + @SuppressWarnings("unchecked") + private Either createModuleNodeTemplateReg(Object regObject) { + + UploadReqInfo regTemplateInfo = new UploadReqInfo(); + Either result = Either.left(regTemplateInfo); + + if (regObject instanceof String) { + String nodeTemplateJsonString = (String) regObject; + regTemplateInfo.setNode(nodeTemplateJsonString); + } else if (regObject instanceof Map) { + Map nodeTemplateJsonMap = (Map) regObject; + // Type + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + // US740820 Relate RIs according to capability name + if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { + regTemplateInfo.setCapabilityName( + (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); + } + } + return result; + } + + public Either propagateStateToCertified(User user, Resource resource, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, + boolean forceCertificationAllowed) { + + Either result = null; + try { + if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed + && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) { + result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock); + if (result.isRight()) { + return result; + } + resource = result.left().value(); + } + if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) { + Either, ResponseFormat> eitherPopulated = populateToscaArtifacts( + resource, user, false, inTransaction, needLock); + result = eitherPopulated.isLeft() ? Either.left(resource) + : Either.right(eitherPopulated.right().value()); + return result; + } + return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock); + } catch (Exception e) { + log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + + private Either nodeFullCertification(String uniqueId, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + Either result = lifecycleBusinessLogic.changeState(uniqueId, user, + LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock); + if (result.isLeft()) { + result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, + lifecycleChangeInfo, inTransaction, needLock); + } + if (result.isLeft()) { + result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, + lifecycleChangeInfo, inTransaction, needLock); + } + return result; + } + + private Either nodeForceCertification(Resource resource, User user, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, + needLock); + } + + + public Either, ResponseFormat> createOrUpdateResourceByImport( + Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, + CsarInfo csarInfo, String nodeName, boolean isNested) { + + // check if resource already exist + Either latestByName = toscaOperationFacade + .getLatestByName(resource.getName()); + Either, ResponseFormat> result = null; + + // create + if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + + Either latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(resource.getToscaResourceName()); + if (csarInfo != null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() + && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + latestByToscaName = toscaOperationFacade + .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), + csarInfo.getVfResourceName(), nodeName).getRight()); + // update + if (latestByToscaName.isLeft()) { + log.debug("validate derived before update"); + Either eitherValidation = validateNestedDerivedFromDuringUpdate( + latestByToscaName.left().value(), resource, + ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion())); + if (eitherValidation.isRight()) { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } else { + result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, + isNormative, needLock, isNested); + } + } + } + if (result == null && latestByToscaName.isRight() + && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo); + } else if (result == null) { + StorageOperationStatus status = latestByName.right().value(); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + log.debug("resource already exist {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + result = Either.right(responseFormat); + } + + } + + // update + else if (latestByName.isLeft()) { + result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, + isNested); + } + + // error + else { + StorageOperationStatus status = latestByName.right().value(); + log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource); + componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + result = Either.right(responseFormat); + } + return result; + + } + + private Either, ResponseFormat> createResourceByImport(Resource resource, + User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) { + log.debug("resource with name {} does not exist. create new resource", resource.getName()); + Either response = validateResourceBeforeCreate(resource, user, + AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo); + if (response.isRight()) { + return Either.right(response.right().value()); + } + Either createResponse = createResourceByDao(resource, user, + AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction); + if (createResponse.isRight()) { + return Either.right(createResponse.right().value()); + } else { + ImmutablePair resourcePair = new ImmutablePair<>(createResponse.left().value(), + ActionStatus.CREATED); + ASDCKpiApi.countImportResourcesKPI(); + return Either.left(resourcePair); + + } + } + + public boolean isResourceExist(String resourceName) { + Either latestByName = toscaOperationFacade.getLatestByName(resourceName); + return latestByName.isLeft(); + } + + private Either, ResponseFormat> updateExistingResourceByImport( + Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, + boolean isNested) { + String lockedResourceId = oldResource.getUniqueId(); + log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, + oldResource.getVersion(), oldResource.getLifecycleState()); + Either, ResponseFormat> result = null; + try { + if (needLock) { + Either lockResult = lockComponent(lockedResourceId, oldResource, + "Update Resource by Import"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + } + + Either prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, + inTransaction, false); + if (prepareResourceForUpdate.isRight()) { + ResponseFormat responseFormat = prepareResourceForUpdate.right().value(); + log.info("resource {} cannot be updated. reason={}", lockedResourceId, + responseFormat.getFormattedMessage()); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(oldResource.getLifecycleState().name()) + .version(oldResource.getVersion()) + .build()); + result = Either.right(prepareResourceForUpdate.right().value()); + return result; + } + oldResource = prepareResourceForUpdate.left().value(); + + mergeOldResourceMetadataWithNew(oldResource, newResource); + + Either validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, + newResource, inTransaction, isNested); + if (validateFieldsResponse.isRight()) { + result = Either.right(validateFieldsResponse.right().value()); + return result; + } + + validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, + AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + if (validateFieldsResponse.isRight()) { + return Either.right(validateFieldsResponse.right().value()); + } + + // contact info normalization + newResource.setContactId(newResource.getContactId().toLowerCase()); + // non-updatable fields + newResource.setCreatorUserId(user.getUserId()); + newResource.setCreatorFullName(user.getFullName()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setLastUpdaterFullName(user.getFullName()); + newResource.setUniqueId(oldResource.getUniqueId()); + newResource.setVersion(oldResource.getVersion()); + newResource.setInvariantUUID(oldResource.getInvariantUUID()); + newResource.setLifecycleState(oldResource.getLifecycleState()); + newResource.setUUID(oldResource.getUUID()); + newResource.setNormalizedName(oldResource.getNormalizedName()); + newResource.setSystemName(oldResource.getSystemName()); + if (oldResource.getCsarUUID() != null) { + newResource.setCsarUUID(oldResource.getCsarUUID()); + } + if (oldResource.getImportedToscaChecksum() != null) { + newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum()); + } + newResource.setAbstract(oldResource.isAbstract()); + + if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) { + newResource.setDerivedFrom(oldResource.getDerivedFrom()); + } + if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) { + newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); + } + if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) { + newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); + } + // TODO rhalili: handle artifacts here (delete from old resource and + // add for new) + // TODO rbetzer: remove after migration - in case of resources + // created without tosca artifacts - add the placeholders + if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) { + setToscaArtifactsPlaceHolders(newResource, user); + } + Either overrideResource = toscaOperationFacade + .overrideComponent(newResource, oldResource); + + if (overrideResource.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE); + + result = Either.right(responseFormat); + return result; + } + + log.debug("Resource updated successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build()); + + + ImmutablePair resourcePair = new ImmutablePair<>(overrideResource.left().value(), + ActionStatus.OK); + result = Either.left(resourcePair); + return result; + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify"); + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } else if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + if (needLock == true) { + log.debug("unlock resource {}", lockedResourceId); + graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource); + } + } + + } + + /** + * Merge old resource with new. Keep old category and vendor name without + * change + * + * @param oldResource + * @param newResource + */ + private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) { + + // keep old category and vendor name without change + // merge the rest of the resource metadata + if (newResource.getTags() == null || newResource.getTags().isEmpty()) { + newResource.setTags(oldResource.getTags()); + } + + if (newResource.getDescription() == null) { + newResource.setDescription(oldResource.getDescription()); + } + + if (newResource.getVendorRelease() == null) { + newResource.setVendorRelease(oldResource.getVendorRelease()); + } + + if (newResource.getResourceVendorModelNumber() == null) { + newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber()); + } + + if (newResource.getContactId() == null) { + newResource.setContactId(oldResource.getContactId()); + } + + newResource.setCategories(oldResource.getCategories()); + if (newResource.getVendorName() == null) { + newResource.setVendorName(oldResource.getVendorName()); + } + } + + private Either prepareResourceForUpdate(Resource latestResource, User user, + boolean inTransaction, boolean needLock) { + + Either result = Either.left(latestResource); + // check if user can edit resource + if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) { + // checkout + Either changeState = lifecycleBusinessLogic.changeState( + latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock); + result = changeState; + } + + return result; + } + + public Either validateResourceBeforeCreate(Resource resource, User user, + AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) { + + Either eitherValidation = validateResourceFieldsBeforeCreate(user, resource, + actionEnum, inTransaction); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, + inTransaction); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + eitherValidation = validateResourceType(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setContactId(resource.getContactId().toLowerCase()); + if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) { + String resourceSystemName; + if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) { + resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName()); + } else { + resourceSystemName = resource.getSystemName(); + } + resource.setToscaResourceName(CommonBeUtils + .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName)); + } + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + // TODO + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + resource.setInvariantUUID(invariantUUID); + + return Either.left(resource); + } + + private Either validateResourceType(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either eitherResult = Either.left(true); + if (resource.getResourceType() == null) { + log.debug("Invalid resource type for resource"); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } + + private Either validateLifecycleTypesCreate(User user, Resource resource, + AuditingActionEnum actionEnum) { + Either eitherResult = Either.left(true); + if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) { + log.debug("validate interface lifecycle Types Exist"); + Iterator intItr = resource.getInterfaces().values().iterator(); + while (intItr.hasNext() && eitherResult.isLeft()) { + InterfaceDefinition interfaceDefinition = intItr.next(); + String intType = interfaceDefinition.getUniqueId(); + Either eitherCapTypeFound = interfaceTypeOperation + .getInterface(intType); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateLifecycleTypesCreate", "Interface", intType); + log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", + intType, resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate"); + log.debug("request to data model failed with error: {}", + eitherCapTypeFound.right().value().name()); + } + + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + + } + } + return eitherResult; + } + + private Either validateCapabilityTypesCreate(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + boolean inTransaction) { + + Either eitherResult = Either.left(true); + if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) { + log.debug("validate capability Types Exist - capabilities section"); + + for (Entry> typeEntry : resource.getCapabilities().entrySet()) { + + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, + eitherResult, typeEntry, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right().value()); + } + } + } + + if (resource.getRequirements() != null && resource.getRequirements().size() > 0) { + log.debug("validate capability Types Exist - requirements section"); + for (String type : resource.getRequirements().keySet()) { + eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, + resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction); + if (eitherResult.isRight()) { + return Either.right(eitherResult.right().value()); + } + } + } + + return eitherResult; + } + + // @param typeObject- the object to which the validation is done + private Either validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, + AuditingActionEnum actionEnum, Either eitherResult, String type, + boolean inTransaction) { + Either eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(type, inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateCapabilityTypesCreate", "Capability Type", type); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, + resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); + } + log.debug("Trying to get capability type {} failed with error: {}", type, + eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = null; + if (type != null) + errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type); + else + errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, + validationObjects); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + return eitherResult; + } + + private Either validateCapabilityTypeExists(User user, + ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, + Either eitherResult, Entry> typeEntry, + boolean inTransaction) { + Either eitherCapTypeFound = capabilityTypeOperation + .getCapabilityType(typeEntry.getKey(), inTransaction); + if (eitherCapTypeFound.isRight()) { + if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeGraphObjectMissingError( + "Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey()); + log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", + typeEntry.getKey(), resource.getName()); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate"); + } + log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), + eitherCapTypeFound.right().value().name()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, + typeEntry.getKey()); + eitherResult = Either.right(errorResponse); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + } + CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value(); + if (capabilityTypeDefinition.getProperties() != null) { + for (CapabilityDefinition capDef : typeEntry.getValue()) { + List properties = capDef.getProperties(); + if (properties == null || properties.isEmpty()) { + properties = new ArrayList(); + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue()); + properties.add(newProp); + } + } else { + for (Entry prop : capabilityTypeDefinition.getProperties().entrySet()) { + PropertyDefinition porpFromDef = prop.getValue(); + List propsToAdd = new ArrayList<>(); + for (ComponentInstanceProperty cip : properties) { + if (!cip.getName().equals(porpFromDef.getName())) { + ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef); + propsToAdd.add(newProp); + } + } + if (!propsToAdd.isEmpty()) { + properties.addAll(propsToAdd); + } + } + } + capDef.setProperties(properties); + } + } + return eitherResult; + } + + public Either createResourceByDao(Resource resource, User user, + AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) { + // create resource + + // lock new resource name in order to avoid creation resource with same + // name + if (inTransaction == false) { + Either lockResult = lockComponentByName(resource.getSystemName(), resource, + "Create Resource"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult); + } + try { + if (resource.deriveFromGeneric()) { + Either genericResourceEither = handleResourceGenericType(resource); + if (genericResourceEither.isRight()) + return genericResourceEither; + } + + Either respStatus = createResourceTransaction(resource, user, isNormative, + inTransaction); + if (respStatus.isLeft()) { + componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, + respStatus.left().value(), actionEnum); + ASDCKpiApi.countCreatedResourcesKPI(); + } else + componentsUtils.auditResource(respStatus.right().value(), user, resource, actionEnum); + return respStatus; + + } finally { + if (inTransaction == false) { + graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), + NodeTypeEnum.Resource); + } + } + } + + private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditResource(responseFormat, user, persistedResource, actionEnum); + } + + private Either createResourceTransaction(Resource resource, User user, + boolean isNormative, boolean inTransaction) { + // validate resource name uniqueness + log.debug("validate resource name"); + Either eitherValidation = toscaOperationFacade.validateComponentNameExists( + resource.getName(), resource.getResourceType(), resource.getComponentType()); + if (eitherValidation.isRight()) { + log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), + eitherValidation.right().value()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); + return Either.right(errorResponse); + } + if (eitherValidation.left().value()) { + log.debug("resource with name: {}, already exists", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + return Either.right(errorResponse); + } + + log.debug("send resource {} to dao for create", resource.getName()); + + createArtifactsPlaceHolderData(resource, user); + + // + + // enrich object + if (!isNormative) { + log.debug("enrich resource with creator, version and state"); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setVersion(INITIAL_VERSION); + resource.setHighestVersion(true); + if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) + resource.setAbstract(false); + } + + Either createToscaElement = toscaOperationFacade + .createToscaComponent(resource); + if (createToscaElement.isLeft()) { + return Either.left(createToscaElement.left().value()); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource); + + return Either.right(responseFormat); + } + + private void createArtifactsPlaceHolderData(Resource resource, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + + setInformationalArtifactsPlaceHolder(resource, user); + setDeploymentArtifactsPlaceHolder(resource, user); + setToscaArtifactsPlaceHolders(resource, user); + } + + @SuppressWarnings("unchecked") + @Override + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + Resource resource = (Resource) component; + Map artifactMap = resource.getDeploymentArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap(); + } + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration().getDeploymentResourceArtifacts(); + if (deploymentResourceArtifacts != null) { + Iterator> iterator = deploymentResourceArtifacts.entrySet().iterator(); + while (iterator.hasNext()) { + Entry currEntry = iterator.next(); + boolean shouldCreateArtifact = true; + Map artifactDetails = (Map) currEntry.getValue(); + Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES); + if (object != null) { + List artifactTypes = (List) object; + if (!artifactTypes.contains(resource.getResourceType().name())) { + shouldCreateArtifact = false; + continue; + } + } else { + log.info("resource types for artifact placeholder {} were not defined. default is all resources", + currEntry.getKey()); + } + if (shouldCreateArtifact) { + if (artifactsBusinessLogic != null) { + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resource.getUniqueId(), currEntry.getKey(), (Map) currEntry.getValue(), + user, ArtifactGroupTypeEnum.DEPLOYMENT); + if (artifactDefinition != null + && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + } + } + } + resource.setDeploymentArtifacts(artifactMap); + } + + @SuppressWarnings("unchecked") + private void setInformationalArtifactsPlaceHolder(Resource resource, User user) { + Map artifactMap = resource.getArtifacts(); + if (artifactMap == null) { + artifactMap = new HashMap(); + } + String resourceUniqueId = resource.getUniqueId(); + List exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludeResourceCategory(); + List exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration() + .getExcludeResourceType(); + Map informationalResourceArtifacts = ConfigurationManager.getConfigurationManager() + .getConfiguration().getInformationalResourceArtifacts(); + List categories = resource.getCategories(); + boolean isCreateArtifact = true; + if (exludeResourceCategory != null) { + String category = categories.get(0).getName(); + for (String exlude : exludeResourceCategory) { + if (exlude.equalsIgnoreCase(category)) { + isCreateArtifact = false; + break; + } + } + + } + if (isCreateArtifact && exludeResourceType != null) { + String resourceType = resource.getResourceType().name(); + for (String type : exludeResourceType) { + if (type.equalsIgnoreCase(resourceType)) { + isCreateArtifact = false; + break; + } + } + + } + + if (informationalResourceArtifacts != null && isCreateArtifact) { + Set keys = informationalResourceArtifacts.keySet(); + for (String informationalResourceArtifactName : keys) { + Map artifactInfoMap = (Map) informationalResourceArtifacts + .get(informationalResourceArtifactName); + ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo( + resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, + ArtifactGroupTypeEnum.INFORMATIONAL); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + } + } + resource.setArtifacts(artifactMap); + } + + /** + * deleteResource + * + * @param resourceId + * @param user + * @return + */ + public ResponseFormat deleteResource(String resourceId, User user) { + ResponseFormat responseFormat; + Either eitherCreator = validateUserExists(user, "Delete Resource", false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + + Either resourceStatus = toscaOperationFacade.getToscaElement(resourceId); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {}", resourceId); + return componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), ""); + } + + Resource resource = resourceStatus.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either lockResult = lockComponent(resourceId, resource, "Mark resource to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + + result = markComponentToDelete(resource); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + } + + } + + public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + Either eitherCreator = validateUserExists(user, "Delete Resource", false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + + Resource resource = null; + StorageOperationStatus result = StorageOperationStatus.OK; + try { + + Either resourceStatus = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version); + if (resourceStatus.isRight()) { + log.debug("failed to get resource {} version {}", resourceName, version); + return componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName); + } + + resource = resourceStatus.left().value(); + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + if (resource != null) { + Either lockResult = lockComponent(resource.getUniqueId(), resource, + "Delete Resource"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + try { + result = markComponentToDelete(resource); + if (!result.equals(StorageOperationStatus.OK)) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName()); + return responseFormat; + } + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource); + } + } + return responseFormat; + } + + public Either getResource(String resourceId, User user) { + + if (user != null) { + Either eitherCreator = validateUserExists(user, "Create Resource", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + } + + Either storageStatus = toscaOperationFacade.getToscaElement(resourceId); + if (storageStatus.isRight()) { + log.debug("failed to get resource by id {}", resourceId); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId)); + } + if (!(storageStatus.left().value() instanceof Resource)) { + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId)); + } + return Either.left(storageStatus.left().value()); + + } + + public Either getResourceByNameAndVersion(String resourceName, String resourceVersion, + String userId) { + + Either resp = validateUserExists(userId, "get Resource By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either getResource = toscaOperationFacade + .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion); + if (getResource.isRight()) { + log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName)); + } + return Either.left(getResource.left().value()); + } + + /** + * updateResourceMetadata + * + * @param user - modifier data (userId) + * @param inTransaction TODO + * @param resourceIdToUpdate - the resource identifier + * @param newResource + * @return Either + */ + public Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, + Resource currentResource, User user, boolean inTransaction) { + + Either resp = validateUserExists(user.getUserId(), "update Resource Metadata", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("Get resource with id {}", resourceIdToUpdate); + boolean needToUnlock = false; + boolean rollbackNeeded = true; + + try { + if (currentResource == null) { + Either storageStatus = toscaOperationFacade + .getToscaElement(resourceIdToUpdate); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus.right().value()), "")); + } + + currentResource = storageStatus.left().value(); + } + // verify that resource is checked-out and the user is the last + // updater + if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + // lock resource + StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, + NodeTypeEnum.Resource); + if (!lockResult.equals(StorageOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", + NodeTypeEnum.Resource.getName(), resourceIdToUpdate); + log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult)); + return Either.right(responseFormat); + } + + needToUnlock = true; + + // critical section starts here + // convert json to object + + // Update and updated resource must have a non-empty "derivedFrom" + // list + // This code is not called from import resources, because of root + // VF "derivedFrom" should be null (or ignored) + if (ModelConverter.isAtomicComponent(currentResource)) { + Either derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, + newResource, null); + if (derivedFromNotEmptyEither.isRight()) { + log.debug("for updated resource {}, derived from field is empty", newResource.getName()); + return Either.right(derivedFromNotEmptyEither.right().value()); + } + + derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null); + if (derivedFromNotEmptyEither.isRight()) { + log.debug("for current resource {}, derived from field is empty", currentResource.getName()); + return Either.right(derivedFromNotEmptyEither.right().value()); + } + } else { + newResource.setDerivedFrom(null); + } + + Either dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, + user, currentResource, false, true); + if (dataModelResponse.isRight()) { + log.debug("failed to update resource metadata!!!"); + rollbackNeeded = true; + return Either.right(dataModelResponse.right().value()); + } + + log.debug("Resource metadata updated successfully!!!"); + rollbackNeeded = false; + return Either.left(dataModelResponse.left().value()); + + } finally { + if (!inTransaction) { + if (rollbackNeeded) { + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + + if (needToUnlock) { + graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource); + } + } + } + + private Either, Boolean> updateComponentGroupName(String replacePattern, String with, + List oldGroup) { + if (oldGroup == null || with == null || replacePattern == null || with.isEmpty() || replacePattern.isEmpty()) { + if (log.isInfoEnabled()) + log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}", + replacePattern, with, oldGroup == null ? null : " < size : " + oldGroup.size() + " >"); + return Either.right(false); + } + List list = oldGroup.stream().map(group -> new GroupDefinition(group)) + .collect(Collectors.toList()); + for (GroupDefinition group : list) { + if (group != null && group.isSamePrefix(replacePattern)) { + String prefix = group.getName().substring(0, replacePattern.length()); + String newGroupName = group.getName().replaceFirst(prefix, with); + group.setName(newGroupName); + } + } + return Either.left(list); + } + + private boolean isComponentNameChanged(Resource newResource, Resource oldResource) { + if (newResource != null && oldResource != null) { // TODO - must protect + // all chain against + // null , use + // optional + String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + return !oldName.equals(futureName); + } + return false; + } + + private Either updateResourceMetadata(String resourceIdToUpdate, Resource newResource, + User user, Resource currentResource, boolean shouldLock, boolean inTransaction) { + // region -> Update groups name for newResource + if (isComponentNameChanged(currentResource, newResource)) { + String replacePattern = Optional.ofNullable( // get currentResource + // name from + // metadata + Optional.ofNullable( + Optional.ofNullable(currentResource).orElse(null).getComponentMetadataDefinition()) + .orElse(null).getMetadataDataDefinition()) + .orElse(null).getName(); + String with = Optional.ofNullable( // get newResource name from + // metadata + Optional.ofNullable(Optional.ofNullable(newResource).orElse(null).getComponentMetadataDefinition()) + .orElse(null).getMetadataDataDefinition()) + .orElse(null).getName(); + if (with != null && replacePattern != null) { + Either, Boolean> result = updateComponentGroupName(replacePattern, with, + currentResource.getGroups()); + if (result.isLeft()) + newResource.setGroups((List) result.left().value()); + } + } + // endregion + + Either validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, + newResource, inTransaction, false); + if (validateResourceFields.isRight()) { + return Either.right(validateResourceFields.right().value()); + } + // Setting last updater and uniqueId + newResource.setContactId(newResource.getContactId().toLowerCase()); + newResource.setLastUpdaterUserId(user.getUserId()); + newResource.setUniqueId(resourceIdToUpdate); + // Cannot set highest version through UI + newResource.setHighestVersion(currentResource.isHighestVersion()); + newResource.setCreationDate(currentResource.getCreationDate()); + + Either processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, + newResource, user.getUserId(), shouldLock, inTransaction); + + if (processUpdateOfDerivedFrom.isRight()) { + log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate); + return Either.right(processUpdateOfDerivedFrom.right().value()); + } + + log.debug("send resource {} to dao for update", newResource.getUniqueId()); + if (newResource != null && newResource.getGroups() != null) { + for (GroupDefinition group : newResource.getGroups()) { + if (newResource.getComponentMetadataDefinition() != null + && newResource.getComponentMetadataDefinition().getMetadataDataDefinition() != null) + groupBusinessLogic.validateAndUpdateGroupMetadata( + newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), + user, ComponentTypeEnum.RESOURCE_INSTANCE, group, true, false); + } + } + Either dataModelResponse = toscaOperationFacade + .updateToscaElement(newResource); + + if (dataModelResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource); + return Either.right(responseFormat); + } else if (dataModelResponse.left().value() == null) { + log.debug("No response from updateResource"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return Either.left(dataModelResponse.left().value()); + } + + /** + * validateResourceFieldsBeforeCreate + * + * @param user - modifier data (userId) + * @return Either + */ + private Either validateResourceFieldsBeforeCreate(User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + Either componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, + actionEnum); + if (componentsFieldsValidation.isRight()) { + return componentsFieldsValidation; + } + + + // validate category + log.debug("validate category"); + Either eitherValidation = validateCategory(user, resource, actionEnum, inTransaction); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate vendor name & release & model number + log.debug("validate vendor name"); + eitherValidation = validateVendorName(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor release"); + eitherValidation = validateVendorReleaseName(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate resource vendor model number"); + eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + + // validate cost + log.debug("validate cost"); + eitherValidation = validateCost(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate licenseType + log.debug("validate licenseType"); + eitherValidation = validateLicenseType(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate template (derived from) + log.debug("validate derived from"); + if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + resource.setDerivedFrom(null); + } + eitherValidation = validateDerivedFromExist(user, resource, actionEnum); + if (eitherValidation.isRight()) { + return Either.right(eitherValidation.right().value()); + } + + // warn about non-updatable fields + checkComponentFieldsForOverrideAttempt(resource); + String currentCreatorFullName = resource.getCreatorFullName(); + if (currentCreatorFullName != null) { + log.warn("Resource Creator fullname is automatically set and cannot be updated"); + } + + String currentLastUpdaterFullName = resource.getLastUpdaterFullName(); + if (currentLastUpdaterFullName != null) { + log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + + Long currentLastUpdateDate = resource.getLastUpdateDate(); + if (currentLastUpdateDate != null) { + log.warn("Resource last update date is automatically set and cannot be updated"); + } + + Boolean currentAbstract = resource.isAbstract(); + if (currentAbstract != null) { + log.warn("Resource abstract is automatically set and cannot be updated"); + } + + return Either.left(true); + } + + /** + * validateResourceFieldsBeforeUpdate + * + * @param currentResource - Resource object to validate + * @param isNested + * @return Either + */ + private Either validateResourceFieldsBeforeUpdate(Resource currentResource, + Resource updateInfoResource, boolean inTransaction, boolean isNested) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion()); + + // validate resource name + log.debug("validate resource name before update"); + Either eitherValidation = validateResourceName(currentResource, updateInfoResource, + hasBeenCertified, isNested); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // validate description + log.debug("validate description before update"); + eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate icon before update"); + eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate tags before update"); + eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor name before update"); + eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate resource vendor model number before update"); + eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate vendor release before update"); + eitherValidation = validateVendorReleaseName(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate contact info before update"); + eitherValidation = validateContactId(null, updateInfoResource, null); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate derived before update"); + eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + log.debug("validate category before update"); + eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction); + if (eitherValidation.isRight()) { + return eitherValidation; + } + + // warn about non-updatable fields + String currentResourceVersion = currentResource.getVersion(); + String updatedResourceVersion = updateInfoResource.getVersion(); + + if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) { + log.warn("Resource version is automatically set and cannot be updated"); + } + + String currentCreatorUserId = currentResource.getCreatorUserId(); + String updatedCreatorUserId = updateInfoResource.getCreatorUserId(); + + if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) { + log.warn("Resource Creator UserId is automatically set and cannot be updated"); + } + + String currentCreatorFullName = currentResource.getCreatorFullName(); + String updatedCreatorFullName = updateInfoResource.getCreatorFullName(); + + if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) { + log.warn("Resource Creator fullname is automatically set and cannot be updated"); + } + + String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId(); + String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId(); + + if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) { + log.warn("Resource LastUpdater userId is automatically set and cannot be updated"); + } + + String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName(); + String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName(); + + if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) { + log.warn("Resource LastUpdater fullname is automatically set and cannot be updated"); + } + + Long currentCreationDate = currentResource.getCreationDate(); + Long updatedCreationDate = updateInfoResource.getCreationDate(); + + if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) { + log.warn("Resource Creation date is automatically set and cannot be updated"); + } + + Long currentLastUpdateDate = currentResource.getLastUpdateDate(); + Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate(); + + if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) { + log.warn("Resource last update date is automatically set and cannot be updated"); + } + + LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState(); + LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState(); + + if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) { + log.warn("Resource lifecycle state date is automatically set and cannot be updated"); + } + + Boolean currentAbstract = currentResource.isAbstract(); + Boolean updatedAbstract = updateInfoResource.isAbstract(); + + if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) { + log.warn("Resource abstract is automatically set and cannot be updated"); + } + + Boolean currentHighestVersion = currentResource.isHighestVersion(); + Boolean updatedHighestVersion = updateInfoResource.isHighestVersion(); + + if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) { + log.warn("Resource highest version is automatically set and cannot be updated"); + } + + String currentUuid = currentResource.getUUID(); + String updatedUuid = updateInfoResource.getUUID(); + + if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) { + log.warn("Resource UUID is automatically set and cannot be updated"); + } + + ResourceTypeEnum currentResourceType = currentResource.getResourceType(); + ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType(); + + if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) { + log.warn("Resource Type cannot be updated"); + + } + updateInfoResource.setResourceType(currentResource.getResourceType()); + + String currentInvariantUuid = currentResource.getInvariantUUID(); + String updatedInvariantUuid = updateInfoResource.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Resource invariant UUID is automatically set and cannot be updated"); + updateInfoResource.setInvariantUUID(currentInvariantUuid); + } + return Either.left(true); + } + + + private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) { + String resourceNameUpdated = updateInfoResource.getName(); + String resourceNameCurrent = currentResource.getName(); + if (resourceNameCurrent.equals(resourceNameUpdated)) + return true; + // In case of CVFC type we should support the case of old VF with CVFC + // instances that were created without the "Cvfc" suffix + return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) && + resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)); + } + + private String addCvfcSuffixToResourceName(String resourceName) { + return resourceName + "Cvfc"; + } + + private Either validateResourceName(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified, boolean isNested) { + String resourceNameUpdated = updateInfoResource.getName(); + if (!isResourceNameEquals(currentResource, updateInfoResource)) { + if (isNested || !hasBeenCertified) { + Either validateResourceNameResponse = validateComponentName(null, + updateInfoResource, null); + if (validateResourceNameResponse.isRight()) { + ResponseFormat errorResponse = validateResourceNameResponse.right().value(); + return Either.right(errorResponse); + } + validateResourceNameResponse = validateResourceNameExists(updateInfoResource); + if (validateResourceNameResponse.isRight()) { + ResponseFormat errorResponse = validateResourceNameResponse.right().value(); + return Either.right(errorResponse); + } + currentResource.setName(resourceNameUpdated); + currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated)); + currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated)); + + } else { + log.info("Resource name: {}, cannot be updated once the resource has been certified once.", + resourceNameUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateIcon(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified) { + String iconUpdated = updateInfoResource.getIcon(); + String iconCurrent = currentResource.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either validateIcon = validateIcon(null, updateInfoResource, null); + if (validateIcon.isRight()) { + ResponseFormat errorResponse = validateIcon.right().value(); + return Either.right(errorResponse); + } + } else { + log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateVendorName(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified) { + String vendorNameUpdated = updateInfoResource.getVendorName(); + String vendorNameCurrent = currentResource.getVendorName(); + if (!vendorNameCurrent.equals(vendorNameUpdated)) { + if(updateInfoResource.getResourceType().equals(ResourceTypeEnum.VF) && hasBeenCertified ){ + log.info("Vendor name {} cannot be updated once the resource has been certified once.", + vendorNameUpdated); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + + } + else { + Either validateVendorName = validateVendorName(null, updateInfoResource, null); + if (validateVendorName.isRight()) { + ResponseFormat errorResponse = validateVendorName.right().value(); + return Either.right(errorResponse); + } + } + } + return Either.left(true); + } + + private Either validateResourceVendorModelNumber(Resource currentResource, + Resource updateInfoResource) { + String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber(); + String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber(); + if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) { + Either validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, + updateInfoResource, null); + if (validateResourceVendorModelNumber.isRight()) { + ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value(); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateCategory(Resource currentResource, Resource updateInfoResource, + boolean hasBeenCertified, boolean inTransaction) { + Either validateCategoryName = validateCategory(null, updateInfoResource, null, + inTransaction); + if (validateCategoryName.isRight()) { + ResponseFormat errorResponse = validateCategoryName.right().value(); + return Either.right(errorResponse); + } + if (hasBeenCertified) { + CategoryDefinition currentCategory = currentResource.getCategories().get(0); + SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0); + CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0); + SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0); + if (!currentCategory.getName().equals(updateCategory.getName()) + || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) { + log.info("Category {} cannot be updated once the resource has been certified once.", + currentResource.getCategories()); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { + + List currentDerivedFrom = currentResource.getDerivedFrom(); + List updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } + + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + Either validateDerivedFromExistsEither = validateDerivedFromExist(null, + updateInfoResource, null); + if (validateDerivedFromExistsEither.isRight()) { + return validateDerivedFromExistsEither; + } + } else { + Either validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } else { + // For derived from, we must know whether it was actually changed, + // otherwise we must do no action. + // Due to changes it inflicts on data model (remove artifacts, + // properties...), it's not like a flat field which can be + // overwritten if not changed. + // So we must indicate that derived from is not changed + updateInfoResource.setDerivedFrom(null); + } + return Either.left(true); + } + + private Either validateNestedDerivedFromDuringUpdate(Resource currentResource, + Resource updateInfoResource, boolean hasBeenCertified) { + + List currentDerivedFrom = currentResource.getDerivedFrom(); + List updatedDerivedFrom = updateInfoResource.getDerivedFrom(); + if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null + || updatedDerivedFrom.isEmpty()) { + log.trace("Update normative types"); + return Either.left(true); + } + + String derivedFromCurrent = currentDerivedFrom.get(0); + String derivedFromUpdated = updatedDerivedFrom.get(0); + + if (!derivedFromCurrent.equals(derivedFromUpdated)) { + if (!hasBeenCertified) { + Either validateDerivedFromExistsEither = validateDerivedFromExist(null, + updateInfoResource, null); + if (validateDerivedFromExistsEither.isRight()) { + return validateDerivedFromExistsEither; + } + } else { + Either validateDerivedFromExtending = validateDerivedFromExtending(null, + currentResource, updateInfoResource, null); + + if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) { + log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance"); + return validateDerivedFromExtending; + } + } + } + return Either.left(true); + } + + private Either validateDerivedFromExist(User user, Resource resource, + AuditingActionEnum actionEnum) { + + if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) { + return Either.left(true); + } + + + String templateName = resource.getDerivedFrom().get(0); + + Either dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExists(templateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist"); + log.debug("request to data model failed with error: {}", storageStatus); + ResponseFormat responseFormat = componentsUtils + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } else if (!dataModelResponse.left().value()) { + log.info("resource template with name: {}, does not exists", templateName); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + + return Either.right(responseFormat); + + } + return Either.left(true); + } + + // Tal G for extending inheritance US815447 + private Either validateDerivedFromExtending(User user, Resource currentResource, + Resource updateInfoResource, AuditingActionEnum actionEnum) { + String currentTemplateName = currentResource.getDerivedFrom().get(0); + String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0); + + Either dataModelResponse = toscaOperationFacade + .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName); + if (dataModelResponse.isRight()) { + StorageOperationStatus storageStatus = dataModelResponse.right().value(); + BeEcompErrorManager.getInstance() + .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType"); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(storageStatus), currentResource); + log.trace("audit before sending response"); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + return Either.right(responseFormat); + } + + if (!dataModelResponse.left().value()) { + log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, + currentTemplateName); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum); + + return Either.right(responseFormat); + + } + return Either.left(true); + } + + public Either validateDerivedFromNotEmpty(User user, Resource resource, + AuditingActionEnum actionEnum) { + log.debug("validate resource derivedFrom field"); + if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) + || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) { + log.info("derived from (template) field is missing for the resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + + return Either.right(responseFormat); + } + return Either.left(true); + } + + private Either validateResourceNameExists(Resource resource) { + + Either resourceOperationResponse = toscaOperationFacade + .validateComponentNameExists(resource.getName(), resource.getResourceType(), + resource.getComponentType()); + if (resourceOperationResponse.isLeft()) { + if (!resourceOperationResponse.left().value()) { + return Either.left(false); + } else { + log.debug("resource with name: {}, already exists", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), + resource.getName()); + return Either.right(errorResponse); + } + } + log.debug("error while validateResourceNameExists for resource: {}", resource.getName()); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value())); + return Either.right(errorResponse); + } + + + private Either validateCategory(User user, Resource resource, + AuditingActionEnum actionEnum, boolean inTransaction) { + + List categories = resource.getCategories(); + if (categories == null || categories.size() == 0) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + if (categories.size() > 1) { + log.debug("Must be only one category for resource"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue()); + return Either.right(responseFormat); + } + CategoryDefinition category = categories.get(0); + List subcategories = category.getSubcategories(); + if (subcategories == null || subcategories.size() == 0) { + log.debug("Missinig subcategory for resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY); + return Either.right(responseFormat); + } + if (subcategories.size() > 1) { + log.debug("Must be only one sub category for resource"); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES); + return Either.right(responseFormat); + } + + SubCategoryDefinition subcategory = subcategories.get(0); + + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + Either validateCategory = validateCategoryListed(category, subcategory, inTransaction); + if (validateCategory.isRight()) { + ResponseFormat responseFormat = validateCategory.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + return Either.right(responseFormat); + } + + return Either.left(true); + } + + private Either validateCategoryListed(CategoryDefinition category, + SubCategoryDefinition subcategory, boolean inTransaction) { + if (category != null && subcategory != null) { + log.debug("validating resource category {} against valid categories list", category); + Either, ActionStatus> categories = elementDao + .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction); + if (categories.isRight()) { + log.debug("failed to retrive resource categories from Titan"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value()); + return Either.right(responseFormat); + } + List categoryList = categories.left().value(); + for (CategoryDefinition cat : categoryList) { + if (cat.getName().equals(category.getName())) { + for (SubCategoryDefinition subcat : cat.getSubcategories()) { + if (subcat.getName().equals(subcategory.getName())) { + return Either.left(true); + } + } + log.debug( + "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", + subcategory, cat.getSubcategories()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue())); + } + } + log.debug("Category {} is not part of resource category group. Resource category valid values are {}", + category, categoryList); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, + ComponentTypeEnum.RESOURCE.getValue())); + } + return Either.left(false); + } + + public Either validateVendorReleaseName(User user, Resource resource, + AuditingActionEnum actionEnum) { + String vendorRelease = resource.getVendorRelease(); + + log.debug("validate vendor relese name"); + if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) { + log.info("vendor relese name is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + + Either validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease); + if (validateVendorReleaseResponse.isRight()) { + ResponseFormat responseFormat = validateVendorReleaseResponse.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateVendorReleaseResponse; + } + + public Either validateVendorReleaseName(String vendorRelease) { + if (vendorRelease != null) { + if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) { + log.info("vendor release exceds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateVendorRelease(vendorRelease)) { + log.info("vendor release is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE); + return Either.right(errorResponse); + } + return Either.left(true); + } + return Either.left(false); + + } + + private Either validateVendorName(User user, Resource resource, + AuditingActionEnum actionEnum) { + String vendorName = resource.getVendorName(); + if (!ValidationUtils.validateStringNotEmpty(vendorName)) { + log.info("vendor name is missing."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME); + componentsUtils.auditResource(errorResponse, user, resource, actionEnum); + return Either.right(errorResponse); + } + + Either validateVendorNameResponse = validateVendorName(vendorName); + if (validateVendorNameResponse.isRight()) { + ResponseFormat responseFormat = validateVendorNameResponse.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateVendorNameResponse; + + } + + private Either validateResourceVendorModelNumber(User user, Resource resource, + AuditingActionEnum actionEnum) { + String resourceVendorModelNumber = resource.getResourceVendorModelNumber(); + Either validateResourceVendorModelNumber = validateResourceVendorModelNumber( + resourceVendorModelNumber); + if (validateResourceVendorModelNumber.isRight()) { + ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value(); + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return validateResourceVendorModelNumber; + + } + + private Either validateVendorName(String vendorName) { + if (vendorName != null) { + if (!ValidationUtils.validateVendorNameLength(vendorName)) { + log.info("vendor name exceds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, + "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateVendorName(vendorName)) { + log.info("vendor name is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME); + return Either.right(errorResponse); + } + return Either.left(true); + + } + return Either.left(false); + + } + + private Either validateResourceVendorModelNumber(String resourceVendorModelNumber) { + if (StringUtils.isEmpty(resourceVendorModelNumber)) { + return Either.left(true); + } else { + if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) { + log.info("resource vendor model number exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat( + ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, + "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + return Either.right(errorResponse); + } + // resource vendor model number is currently validated as vendor + // name + if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) { + log.info("resource vendor model number is not valid."); + ResponseFormat errorResponse = componentsUtils + .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + + private Either validateCost(User user, Resource resource, AuditingActionEnum actionEnum) { + String cost = resource.getCost(); + if (cost != null) { + + if (!ValidationUtils.validateCost(cost)) { + log.debug("resource cost is invalid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateLicenseType(User user, Resource resource, + AuditingActionEnum actionEnum) { + log.debug("validate licenseType"); + String licenseType = resource.getLicenseType(); + if (licenseType != null) { + List licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration() + .getLicenseTypes(); + if (!licenseTypes.contains(licenseType)) { + log.debug("License type {} isn't configured"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + if (actionEnum != null) { + // In update case, no audit is required + componentsUtils.auditResource(responseFormat, user, resource, actionEnum); + } + return Either.right(responseFormat); + } + } + return Either.left(true); + } + + private Either processUpdateOfDerivedFrom(Resource currentResource, + Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) { + Either deleteArtifactByInterface = null; + if (updatedResource.getDerivedFrom() != null) { + log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId()); + log.debug("1. Removing interface artifacts from graph"); + // Remove all interface artifacts of resource + String resourceId = updatedResource.getUniqueId(); + Map interfaces = currentResource.getInterfaces(); + + if (interfaces != null) { + Collection values = interfaces.values(); + for (InterfaceDefinition interfaceDefinition : values) { + String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition); + + log.trace("Starting interface artifacts removal for interface type {}", interfaceType); + Map operations = interfaceDefinition.getOperationsMap(); + if (operations != null) { + for (Entry operationEntry : operations.entrySet()) { + Operation operation = operationEntry.getValue(); + ArtifactDefinition implementation = operation.getImplementationArtifact(); + if (implementation != null) { + String uniqueId = implementation.getUniqueId(); + log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", + uniqueId, operationEntry.getKey(), interfaceType); + // only thing that transacts and locks here + deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, + userId, uniqueId, + true); + if (deleteArtifactByInterface.isRight()) { + log.debug("Couldn't remove artifact definition with id {}", uniqueId); + if (!inTransaction) { + titanDao.rollback(); + } + return Either.right(deleteArtifactByInterface.right().value()); + } + } else { + log.trace("No implementation found for operation {} - nothing to delete", + operationEntry.getKey()); + } + } + } else { + log.trace("No operations found for interface type {}", interfaceType); + } + } + } + log.debug("2. Removing properties"); + Either, StorageOperationStatus> findPropertiesOfNode = propertyOperation + .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId); + + if (findPropertiesOfNode.isRight() + && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) { + log.debug("Failed to remove all properties of resource"); + if (!inTransaction) + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value()))); + } + + } else { + log.debug("Derived from wasn't changed during update"); + } + + if (!inTransaction) + titanDao.commit(); + return Either.left(true); + + } + + /**** Auditing *******************/ + + protected static IElementOperation getElementDao(Class class1, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(class1); + } + + public ICapabilityTypeOperation getCapabilityTypeOperation() { + return capabilityTypeOperation; + } + + public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) { + this.capabilityTypeOperation = capabilityTypeOperation; + } + + public Either validatePropertiesDefaultValues(Resource resource) { + log.debug("validate resource properties default values"); + Either eitherResult = Either.left(true); + List properties = resource.getProperties(); + String type = null; + String innerType = null; + if (properties != null) { + for (PropertyDefinition property : properties) { + if (!propertyOperation.isPropertyTypeValid(property)) { + log.info("Invalid type for property"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()); + eitherResult = Either.right(responseFormat); + break; + } + + Either, ResponseFormat> allDataTypes = getAllDataTypes( + applicationDataTypeCache); + if (allDataTypes.isRight()) { + return Either.right(allDataTypes.right().value()); + } + + type = property.getType(); + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + ImmutablePair propertyInnerTypeValid = propertyOperation + .isPropertyInnerTypeValid(property, allDataTypes.left().value()); + innerType = propertyInnerTypeValid.getLeft(); + if (!propertyInnerTypeValid.getRight().booleanValue()) { + log.info("Invalid inner type for property"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); + eitherResult = Either.right(responseFormat); + break; + } + } + + if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) { + log.info("Invalid default value for property"); + ResponseFormat responseFormat; + if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, + property.getName(), type, innerType, property.getDefaultValue()); + } else { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, + property.getName(), type, property.getDefaultValue()); + } + eitherResult = Either.right(responseFormat); + break; + + } + } + } + return eitherResult; + } + + @Override + public Either, ResponseFormat> deleteMarkedComponents() { + return deleteMarkedComponents(ComponentTypeEnum.RESOURCE); + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + private String getComponentTypeForResponse(Component component) { + String componentTypeForResponse = "SERVICE"; + if (component instanceof Resource) { + componentTypeForResponse = ((Resource) component).getResourceType().name(); + } + return componentTypeForResponse; + } + + private Either, ResponseFormat> createGroupsFromYaml(String yamlFileName, + Map toscaJson, Resource resource) { + + Map groups = new HashMap(); + Either, ResponseFormat> result = Either.left(groups); + + Either, ResultStatusEnum> eitherNodesTemlates = ImportUtils + .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS); + if (eitherNodesTemlates.isLeft()) { + Map jsonNodeTemplates = eitherNodesTemlates.left().value(); + + if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) { + Iterator> nodesNameValue = jsonNodeTemplates.entrySet().iterator(); + while (nodesNameValue.hasNext()) { + Entry groupNameValue = nodesNameValue.next(); + + String groupName = groupNameValue.getKey(); + Either eitherNode = createGroupInfo(groupName, + groupNameValue.getValue()); + if (eitherNode.isRight()) { + String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + + resource.getName(); + BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, + ErrorSeverity.INFO); + return Either.right(eitherNode.right().value()); + } else { + GroupDefinition groupDefinition = eitherNode.left().value(); + groups.put(groupName, groupDefinition); + } + } + } + } + + return result; + } + + private Either, ResponseFormat> createInputsFromYaml(String yamlFileName, + Map toscaJson, Resource resource) { + + Either, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson); + if (inputs.isRight()) { + String message = "Failed when creating inputs: for resource:" + resource.getName(); + BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO); + Map resultMap = new HashMap<>(); + return Either.left(resultMap); + + } + + Either, ResponseFormat> result = Either.left(inputs.left().value()); + + return result; + } + + @SuppressWarnings("unchecked") + private Either createGroupInfo(String groupName, Object groupTemplateJson) { + + GroupDefinition groupInfo = new GroupDefinition(); + groupInfo.setName(groupName); + Either result = Either.left(groupInfo); + + try { + if (groupTemplateJson != null && groupTemplateJson instanceof Map) { + Map groupTemplateJsonMap = (Map) groupTemplateJson; + String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); + if (!StringUtils.isEmpty(groupType)) { + groupInfo.setType(groupType); + } else { + log.debug("The 'type' member is not found under group {}", groupName); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName)); + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + groupInfo.setDescription( + (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) { + Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName()); + if (members != null) { + if (members instanceof List) { + Map membersLoaded = new HashMap<>(); + List membersAsList = (List) members; + for (Object member : membersAsList) { + membersLoaded.put(member.toString(), ""); + } + groupInfo.setMembers(membersLoaded); + } else { + log.debug("The 'members' member is not of type list under group {}", groupName); + return Either + .right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + } + } + + if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName()); + + Either, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml( + properties, groupName, groupType); + if (regResponse.isRight()) + return Either.right(regResponse.right().value()); + if (regResponse.left().value().size() > 0) { + groupInfo.convertFromGroupProperties(regResponse.left().value()); + } + } + + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group"); + log.debug("error when creating group, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + @SuppressWarnings("unchecked") + private Either, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, + String groupName, String groupType) { + + List result = new ArrayList<>(); + + if (properties == null) { + return Either.left(result); + } + + Either groupTypeRes = groupTypeOperation + .getLatestGroupTypeByType(groupType, true); + + if (groupTypeRes.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); + } + + Map gtProperties = new HashMap<>(); + GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); + + List propertiesDef = groupTypeDefinition.getProperties(); + + if (propertiesDef != null) { + gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + } + + if (properties != null) { + + if (properties instanceof Map) { + + Map props = (Map) properties; + for (Entry entry : props.entrySet()) { + + String propName = entry.getKey(); + Object value = entry.getValue(); + + PropertyDefinition gtDefinition = gtProperties.get(propName); + if (gtDefinition == null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, + propName, groupName, groupType)); + } + + ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType()); + + String convertedValue = null; + if (value != null) { + if (type == null || value instanceof Map || value instanceof List) { + convertedValue = gson.toJson(value); + } else { + convertedValue = value.toString(); + } + } + + GroupProperty groupProperty = new GroupProperty(); + groupProperty.setValue(convertedValue); + groupProperty.setName(propName); + + log.trace("After building group property {}", groupProperty); + + result.add(groupProperty); + } + + } + + } + + return Either.left(result); + } + + public Either getLatestResourceFromCsarUuid(String csarUuid, User user) { + + // validate user + if (user != null) { + Either userValidation = validateUserExists(user, "Get resource from csar UUID", + false); + if (userValidation.isRight()) { + return Either.right(userValidation.right().value()); + } + } + + // get resource from csar uuid + Either either = toscaOperationFacade + .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, ""); + if (either.isRight()) { + ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, + csarUuid); + return Either.right(resp); + } + + return Either.left(either.left().value()); + } + + @Override + public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs( + String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + private Either>, ResponseFormat> getValidComponentInstanceCapabilities( + String resourceId, Map> defaultCapabilities, + Map> uploadedCapabilities) { + ResponseFormat responseFormat; + Map> validCapabilitiesMap = new HashMap<>(); + + for (Entry> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) { + String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType(); + if (!defaultCapabilities.containsKey(capabilityType)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, + capabilityType); + return Either.right(responseFormat); + } else { + CapabilityDefinition defaultCapability; + if (CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) { + defaultCapability = defaultCapabilities.get(capabilityType).get(0); + } else { + Either getFullComponentRes = toscaOperationFacade + .getToscaFullElement(resourceId); + if (getFullComponentRes.isRight()) { + log.debug("Failed to get full component {}. Status is {}. ", resourceId, + getFullComponentRes.right().value()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, + resourceId); + return Either.right(responseFormat); + } + defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0); + } + if (CollectionUtils.isEmpty(defaultCapability.getProperties()) + && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) { + log.debug("Failed to validate capability {} of component {}. Property list is empty. ", + defaultCapability.getName(), resourceId); + log.debug( + "Failed to update capability property values. Property list of fetched capability {} is empty. ", + defaultCapability.getName()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId); + return Either.right(responseFormat); + } + if (CollectionUtils.isNotEmpty(defaultCapability.getProperties()) + && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) { + Either validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability( + defaultCapability, uploadedCapabilitiesEntry.getValue().get(0)); + if (validationRes.isRight()) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, + validationRes.right().value()); + return Either.right(responseFormat); + } + } + List validCapabilityList = new ArrayList<>(); + validCapabilityList.add(defaultCapability); + validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList); + } + } + return Either.left(validCapabilitiesMap); + } + + private Either validateUniquenessUpdateUploadedComponentInstanceCapability( + CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) { + List validProperties = new ArrayList<>(); + Map defaultProperties = defaultCapability.getProperties().stream() + .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + List uploadedProperties = uploadedCapability.getProperties(); + for (UploadPropInfo property : uploadedProperties) { + String propertyName = property.getName().toLowerCase(); + String propertyType = property.getType(); + ComponentInstanceProperty validProperty; + if (defaultProperties.containsKey(propertyName)) { + if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) { + return Either.right(propertyName); + } + } + validProperty = new ComponentInstanceProperty(); + validProperty.setName(propertyName); + if (property.getValue() != null) + validProperty.setValue(property.getValue().toString()); + validProperty.setDescription(property.getDescription()); + validProperty.setPassword(property.isPassword()); + validProperties.add(validProperty); + } + defaultCapability.setProperties(validProperties); + return Either.left(true); + } + + private Either>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( + List artifactPathAndNameList, List existingArtifactsToHandle, + Resource resource, User user) { + + EnumMap> nodeTypeArtifactsToHandle = new EnumMap<>( + ArtifactOperationEnum.class); + Wrapper responseWrapper = new Wrapper<>(); + Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either + .left(nodeTypeArtifactsToHandle); + ; + try { + // add all found Csar artifacts to list to upload + List artifactsToUpload = new ArrayList<>(artifactPathAndNameList); + List artifactsToUpdate = new ArrayList<>(); + List artifactsToDelete = new ArrayList<>(); + for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) { + ArtifactDefinition foundArtifact; + + if (!existingArtifactsToHandle.isEmpty()) { + foundArtifact = existingArtifactsToHandle.stream() + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() + .orElse(null); + if (foundArtifact != null) { + if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact + .getArtifactType()) { + if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { + currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); + // if current artifact already exists, but has + // different content, add him to the list to + // update + artifactsToUpdate.add(currNewArtifact); + } + // remove found artifact from the list of existing + // artifacts to handle, because it was already + // handled + existingArtifactsToHandle.remove(foundArtifact); + // and remove found artifact from the list to + // upload, because it should either be updated or be + // ignored + artifactsToUpload.remove(currNewArtifact); + } else { + log.debug("Can't upload two artifact with the same name {}.", + currNewArtifact.getArtifactName()); + ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( + ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(), + foundArtifact.getArtifactType()); + AuditingActionEnum auditingAction = artifactsBusinessLogic + .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, + ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); + artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), + user, null, null, foundArtifact.getUniqueId(), responseFormat, + resource.getComponentType(), null); + responseWrapper.setInnerElement(responseFormat); + break; + } + } + } + } + if (responseWrapper.isEmpty()) { + for (ArtifactDefinition currArtifact : existingArtifactsToHandle) { + if (currArtifact.getIsFromCsar()) { + artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + } else { + artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + + } + } + } + if (responseWrapper.isEmpty()) { + if (!artifactsToUpload.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload); + if (!artifactsToUpdate.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate); + if (!artifactsToDelete.isEmpty()) + nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete); + } + if (!responseWrapper.isEmpty()) { + nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement()); + } + } catch (Exception e) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e); + } + return nodeTypeArtifactsToHandleRes; + } + + private ImmutablePair buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, + String nodeTypeFullName) { + String actualType; + String actualVfName; + if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) { + actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name(); + actualType = ResourceTypeEnum.VFC.name(); + } else { + actualVfName = vfResourceName; + actualType = nodeResourceType; + } + + StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + String nameWithouNamespacePrefix = nodeTypeFullName + .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = nameWithouNamespacePrefix.split("\\."); + String resourceType = findTypes[0]; + String actualName = nameWithouNamespacePrefix.substring(resourceType.length()); + + if (actualName.startsWith(Constants.ABSTRACT)) { + toscaResourceName.append(resourceType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)); + } else { + toscaResourceName.append(actualType.toLowerCase()).append('.') + .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT); + } + StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName); + return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), + previousToscaResourceName + .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()) + .toString()); + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + ///////////////////////////////////////// DataModel + ///////////////////////////////////////// refactoring///////////////////////////////////////////// + @Override + public Either getUiComponentDataTransferByComponentId(String resourceId, + List dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, + paramsToRetuen); + + if (resourceResultEither.isRight()) { + if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found resource with id {} ", resourceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + } + + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn); + return Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); + } + + Resource resource = resourceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, + dataParamsToReturn); + return Either.left(dataTransfer); + } + + @Override + public Either shouldUpgradeToLatestDerived(Component clonedComponent) { + Resource resource = (Resource) clonedComponent; + if (ModelConverter.isAtomicComponent(resource.getResourceType())) { + Either shouldUpgradeToLatestDerived = toscaOperationFacade + .shouldUpgradeToLatestDerived(resource); + if (shouldUpgradeToLatestDerived.isRight()) { + return Either.right( + componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value())); + } + return Either.left(shouldUpgradeToLatestDerived.left().value()); + } else { + return super.shouldUpgradeToLatestDerived(clonedComponent); + } + } + + +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index 7ed90ce3b6..97dcf35c96 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -20,25 +20,12 @@ package org.openecomp.sdc.be.components.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.Constants; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; @@ -71,8 +58,9 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -82,882 +70,919 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; @Component("resourceImportManager") public class ResourceImportManager { - private ServletContext servletContext; - - @Autowired - private IAuditingManager auditingManager; - - @Autowired - private ResourceBusinessLogic resourceBusinessLogic; - - @Autowired - private IGraphLockOperation graphLockOperation; - - @Autowired - protected ComponentsUtils componentsUtils; - - public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern - .compile("[\\w\\-\\_\\d\\:]+"); - @Autowired - protected CapabilityTypeOperation capabilityTypeOperation; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - private ResponseFormatManager responseFormatManager; - - private static Logger log = LoggerFactory.getLogger(ResourceImportManager.class.getName()); - - public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { - this.toscaOperationFacade = toscaOperationFacade; - } - - public Either, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - lifecycleChangeInfo.setUserRemarks("certification on import"); - Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); - } - - public Either, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { - - LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - lifecycleChangeInfo.setUserRemarks("certification on import"); - Function> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); - } - - public Either, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function> validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { - Resource resource = new Resource(); - ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); - Either, ResponseFormat> response = Either.left(responsePair); - - String latestCertifiedResourceId = null; - try { - boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty(); - setConstantMetaData(resource, shouldBeCertified); - setMetaDataFromJson(resourceMetaData, resource); - - Either validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - return Either.right(validationErrorResponse); - - } - - Either isValidResource = validationFunction.apply(resource); - if (isValidResource.isLeft()) { - // The flag createNewVersion if false doesn't create new version - if (!createNewVersion) { - Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); - if (latestByName.isLeft()) { - return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); - } - } - - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested); - Either changeStateResponse; - if (response.isLeft()) { - resource = response.left().value().left; - - if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){ - Either, ResponseFormat> handleNodeTypeArtifactsRes = - resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); - if(handleNodeTypeArtifactsRes.isRight()){ - return Either.right(handleNodeTypeArtifactsRes.right().value()); - } - } - latestCertifiedResourceId = getLatestCertifiedResourceId(resource); - changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); - if (changeStateResponse.isRight()) { - response = Either.right(changeStateResponse.right().value()); - } else { - responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right); - response = Either.left(responsePair); - } - } - } else { - ResponseFormat validationErrorResponse = isValidResource.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); - response = Either.right(validationErrorResponse); - } - - } catch (RuntimeException e) { - ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e); - response = Either.right(exceptionResponse); - } finally { - if (latestCertifiedResourceId != null && needLock) { - log.debug("unlock resource {}", latestCertifiedResourceId); - graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); - } - } - - return response; - } - - private String getLatestCertifiedResourceId(Resource resource) { - Map allVersions = resource.getAllVersions(); - Double latestCertifiedVersion = 0.0; - if (allVersions != null) { - for (String version : allVersions.keySet()) { - Double dVersion = Double.valueOf(version); - if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) { - latestCertifiedVersion = dVersion; - } - } - return allVersions.get(String.valueOf(latestCertifiedVersion)); - } else { - return null; - } - } - - public Either, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isReusable, boolean isInTransaction) { - - Resource resource = new Resource(); - ImmutablePair responsePair = new ImmutablePair(resource, ActionStatus.CREATED); - Either, ResponseFormat> response = Either.left(responsePair); - - try { - setMetaDataFromJson(resourceMetaData, resource); - - Either validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction); - if (validateResourceFromYaml.isRight()) { - ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - return Either.right(validationErrorResponse); - - } - - // currently import VF isn't supported. In future will be supported - // import VF only with CSER file!! - if (ResourceTypeEnum.VF.equals(resource.getResourceType())) { - log.debug("Now import VF isn't supported. It will be supported in future with CSER file only"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); - if (validateDerivedFromNotEmpty.isRight()) { - return Either.right(validateDerivedFromNotEmpty.right().value()); - } - - Either validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); - - if (validatePropertiesTypes.isLeft()) { - response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); - } else { - ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); - auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); - response = Either.right(validationErrorResponse); - } - - } catch (RuntimeException e) { - ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e); - response = Either.right(exceptionResponse); - } - - return response; - - } - - Either populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) { - @SuppressWarnings("unchecked") - Either eitherResult = Either.left(true); - Map toscaJsonAll = (Map) new Yaml().load(resourceYml); - Map toscaJson = toscaJsonAll; - - // Checks if exist and builds the node_types map - if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) { - toscaJson = new HashMap(); - toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName())); - } - // Derived From - Either setDerivedFrom = setDerivedFrom(toscaJson, resource, inTransaction); - if (setDerivedFrom.isRight()) { - return Either.right(setDerivedFrom.right().value()); - } - Resource parentResource = setDerivedFrom.left().value(); - if(StringUtils.isEmpty(resource.getToscaResourceName())) - setToscaResourceName(toscaJson, resource); - setAttributes(toscaJson, resource); - eitherResult = setCapabilities(toscaJson, resource, parentResource); - if (eitherResult.isRight()) - return eitherResult; - eitherResult = setProperties(toscaJson, resource); - if (eitherResult.isRight()) - return eitherResult; - eitherResult = setRequirements(toscaJson, resource, parentResource); - if (eitherResult.isRight()) - return eitherResult; - setInterfaceLifecycle(toscaJson, resource); - - return eitherResult; - } - - private void setToscaResourceName(Map toscaJson, Resource resource) { - Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) { - String toscaResourceName = toscaElement.left().value().keySet().iterator().next(); - resource.setToscaResourceName(toscaResourceName); - } - } - - private void setInterfaceLifecycle(Map toscaJson, Resource resource) { - Either, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES); - if (toscaInterfaces.isLeft()) { - Map jsonInterfaces = toscaInterfaces.left().value(); - Map moduleInterfaces = new HashMap(); - Iterator> interfacesNameValue = jsonInterfaces.entrySet().iterator(); - while (interfacesNameValue.hasNext()) { - Entry interfaceNameValue = interfacesNameValue.next(); - Either eitherInterface = createModuleInterface(interfaceNameValue.getValue()); - if (eitherInterface.isRight()) { - log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); - } else { - moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value()); - } - - } - if (moduleInterfaces.size() > 0) { - resource.setInterfaces(moduleInterfaces); - } - } - } - - private Either createModuleInterface(Object interfaceJson) { - InterfaceDefinition interf = new InterfaceDefinition(); - Either result = Either.left(interf); - - try { - if (interfaceJson instanceof String) { - String requirementJsonString = (String) interfaceJson; - interf.setType(requirementJsonString); - } else if (interfaceJson instanceof Map) { - Map requirementJsonMap = (Map) interfaceJson; - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); - interf.setType(type); - interf.setUniqueId(type.toLowerCase()); - } - } else { - result = Either.right(ResultStatusEnum.GENERAL_ERROR); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource- create interface"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); - log.debug("error when creating interface, message:{}", e.getMessage(), e); - result = Either.right(ResultStatusEnum.GENERAL_ERROR); - } - - return result; - } - - private Either setRequirements(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either eitherResult = Either.left(true); - Either, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS); - if (toscaRequirements.isLeft()) { - List jsonRequirements = toscaRequirements.left().value(); - Map> moduleRequirements = new HashMap>(); - // Checking for name duplication - Set reqNames = new HashSet<>(); - // Getting flattened list of capabilities of parent node - cap name - // to cap type - Either, ResponseFormat> reqName2Type = getReqName2Type(parentResource); - if (reqName2Type.isRight()) { - ResponseFormat responseFormat = reqName2Type.right().value(); - log.debug("Error during setting requirements of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map reqName2TypeMap = reqName2Type.left().value(); - for (Object jsonRequirementObj : jsonRequirements) { - // Requirement - Map requirementJsonWrapper = (Map) jsonRequirementObj; - String requirementName = requirementJsonWrapper.keySet().iterator().next(); - String reqNameLowerCase = requirementName.toLowerCase(); - if (reqNames.contains(reqNameLowerCase)) { - log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase)); - } - reqNames.add(reqNameLowerCase); - Either eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName)); - if (eitherRequirement.isRight()) { - log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName()); - return Either.right(eitherRequirement.right().value()); - } - RequirementDefinition requirementDef = eitherRequirement.left().value(); - requirementDef.setName(requirementName); - if (moduleRequirements.containsKey(requirementDef.getCapability())) { - moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); - } else { - List list = new ArrayList(); - list.add(requirementDef); - moduleRequirements.put(requirementDef.getCapability(), list); - } - - // Validating against req/cap of "derived from" node - Either validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { - log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); - } - } - if (moduleRequirements.size() > 0) { - resource.setRequirements(moduleRequirements); - } - - } - return eitherResult; - - } - - private Either createRequirementFromImportFile(Object requirementJson) { - RequirementDefinition requirement = new RequirementDefinition(); - Either result = Either.left(requirement); - - try { - if (requirementJson instanceof String) { - String requirementJsonString = (String) requirementJson; - requirement.setCapability(requirementJsonString); - } else if (requirementJson instanceof Map) { - Map requirementJsonMap = (Map) requirementJson; - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { - requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); - } - - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { - requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); - } - - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { - requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName())); - } - if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value() == true) { - requirement.setMinOccurrences(occurrencesList.get(0).toString()); - requirement.setMaxOccurrences(occurrencesList.get(1).toString()); - } - - } - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create Requirement"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement"); - log.debug("error when creating requirement, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private Either setProperties(Map toscaJson, Resource resource) { - Map reducedToscaJson = new HashMap<>(toscaJson); - ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - Either result = Either.left(true); - Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); - if (properties.isLeft()) { - List propertiesList = new ArrayList<>(); - Map value = properties.left().value(); - if (value != null) { - for (Entry entry : value.entrySet()) { - String name = entry.getKey(); - if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ - log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); - } - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - propertiesList.add(propertyDefinition); - } - } - resource.setProperties(propertiesList); - } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); - } - return result; - } - - private ResultStatusEnum setAttributes(Map toscaJson, Resource resource) { - ResultStatusEnum result = ResultStatusEnum.OK; - Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); - if (attributes.isLeft()) { - List attributeList = new ArrayList<>(); - Map value = attributes.left().value(); - if (value != null) { - for (Entry entry : value.entrySet()) { - String name = entry.getKey(); - PropertyDefinition attributeDef = entry.getValue(); - attributeDef.setName(name); - attributeList.add(attributeDef); - } - } - resource.setAttributes(attributeList); - } else { - result = attributes.right().value(); - } - return result; - } - - private Either setDerivedFrom(Map toscaJson, Resource resource, boolean inTransaction) { - Either toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM); - Resource derivedFromResource = null; - if (toscaDerivedFromElement.isLeft()) { - String derivedFrom = toscaDerivedFromElement.left().value(); - log.debug("Derived from TOSCA name is {}", derivedFrom); - resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom })); - Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); - - if (latestByToscaResourceName.isRight()) { - StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); - if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { - operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; - } - log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); - ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); - BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); - return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom)); - } - derivedFromResource = latestByToscaResourceName.left().value(); - } - return Either.left(derivedFromResource); - } - - private Either setCapabilities(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either eitherResult = Either.left(true); - Either, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES); - if (toscaCapabilities.isLeft()) { - Map jsonCapabilities = toscaCapabilities.left().value(); - Map> moduleCapabilities = new HashMap>(); - Iterator> capabilitiesNameValue = jsonCapabilities.entrySet().iterator(); - Set capNames = new HashSet<>(); - // Getting flattened list of capabilities of parent node - cap name - // to cap type - Either, ResponseFormat> capName2Type = getCapName2Type(parentResource); - if (capName2Type.isRight()) { - ResponseFormat responseFormat = capName2Type.right().value(); - log.debug("Error during setting capabilities of imported resource: {}", responseFormat); - return Either.right(responseFormat); - } - Map capName2TypeMap = capName2Type.left().value(); - while (capabilitiesNameValue.hasNext()) { - Entry capabilityNameValue = capabilitiesNameValue.next(); - - // Validating that no req/cap duplicates exist in imported YAML - String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); - if (capNames.contains(capNameLowerCase)) { - log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase)); - } - capNames.add(capNameLowerCase); - - Either eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue()); - if (eitherCapability.isRight()) { - log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName()); - return Either.right(eitherCapability.right().value()); - } - - CapabilityDefinition capabilityDef = eitherCapability.left().value(); - capabilityDef.setName(capabilityNameValue.getKey()); - if (moduleCapabilities.containsKey(capabilityDef.getType())) { - moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); - } else { - List list = new ArrayList(); - list.add(capabilityDef); - moduleCapabilities.put(capabilityDef.getType(), list); - } - - // Validating against req/cap of "derived from" node - Either validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName()); - if (validateVsParentCap.isRight()) { - return Either.right(validateVsParentCap.right().value()); - } - if (!validateVsParentCap.left().value()) { - // Here parentResource is for sure not null, so it's - // null-safe - log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName()); - return Either.right(responseFormat); - } - } - if (moduleCapabilities.size() > 0) { - resource.setCapabilities(moduleCapabilities); - } - } - - return eitherResult; - - } - - private Either, ResponseFormat> getCapName2Type(Resource parentResource) { - Map capName2type = new HashMap<>(); - if (parentResource != null) { - Map> capabilities = parentResource.getCapabilities(); - if (capabilities != null) { - for (List capDefinitions : capabilities.values()) { - for (CapabilityDefinition capDefinition : capDefinitions) { - String nameLowerCase = capDefinition.getName().toLowerCase(); - if (capName2type.get(nameLowerCase) != null) { - String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); - BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - capName2type.put(nameLowerCase, capDefinition.getType()); - } - } - } - } - return Either.left(capName2type); - } - - private Either, ResponseFormat> getReqName2Type(Resource parentResource) { - Map reqName2type = new HashMap<>(); - if (parentResource != null) { - Map> requirements = parentResource.getRequirements(); - if (requirements != null) { - for (List reqDefinitions : requirements.values()) { - for (RequirementDefinition reqDefinition : reqDefinitions) { - String nameLowerCase = reqDefinition.getName().toLowerCase(); - if (reqName2type.get(nameLowerCase) != null) { - String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); - BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - reqName2type.put(nameLowerCase, reqDefinition.getCapability()); - } - } - } - } - return Either.left(reqName2type); - } - - private Either validateCapNameVsDerived(Map parentCapName2Type, String childCapabilityType, String reqCapName) { - String capNameLowerCase = reqCapName.toLowerCase(); - log.trace("Validating capability {} vs parent resource", capNameLowerCase); - String parentCapType = parentCapName2Type.get(capNameLowerCase); - if (parentCapType != null) { - if (childCapabilityType.equals(parentCapType)) { - log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); - return Either.left(true); - } - Either capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); - if (capabilityTypeDerivedFrom.isRight()) { - log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value())); - return Either.right(responseFormat); - } - return Either.left(capabilityTypeDerivedFrom.left().value()); - } - return Either.left(true); - } - - private Either createCapabilityFromImportFile(Object capabilityJson) { - - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - Either result = Either.left(capabilityDefinition); - - try { - if (capabilityJson instanceof String) { - String capabilityJsonString = (String) capabilityJson; - capabilityDefinition.setType(capabilityJsonString); - } else if (capabilityJson instanceof Map) { - Map capabilityJsonMap = (Map) capabilityJson; - // Type - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { - capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - capabilityDefinition.setValidSourceTypes((List) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())); - } - // ValidSourceTypes - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); - } - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); - Either validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); - if (validateAndSetOccurrencesStatus.isRight()) { - result = Either.right(validateAndSetOccurrencesStatus.right().value()); - return result; - } - if (validateAndSetOccurrencesStatus.left().value() == true) { - capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); - capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); - } - } - if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { - - Either, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); - if (propertiesRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); - return result; - } else { - propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); - List capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); - capabilityDefinition.setProperties(capabilityProperties); - } - } - } else if (!(capabilityJson instanceof List)) { - - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability"); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); - log.debug("error when creating capability, message:{}", e.getMessage(), e); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); - } - - return result; - } - - private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { - String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : ""; - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource " + payloadName); - BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName); - - log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e); - ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); - auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative); - return errorResponseWrapper; - } - - private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { - EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus()); - String message = ""; - if (errorResponseWrapper.getMessageId() != null) { - message = errorResponseWrapper.getMessageId() + ": "; - } - message += errorResponseWrapper.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); - - String version, lifeCycleState; - if (isNormative) { - version = Constants.FIRST_CERTIFIED_VERSION_VERSION; - lifeCycleState = LifecycleStateEnum.CERTIFIED.name(); - } else { - version = ""; - lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); - - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); - - getAuditingManager().auditEvent(auditingFields); - } - - private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) { - resource.setTags(resourceMetaData.getTags()); - List categories = resourceMetaData.getCategories(); - resource.setCategories(categories); - resource.setDescription(resourceMetaData.getDescription()); - resource.setIcon(resourceMetaData.getResourceIconPath()); - resource.setName(resourceMetaData.getName()); - if (categories != null && !categories.isEmpty()) { - CategoryDefinition categoryDef = categories.get(0); - resource.setAbstract(false); - if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) { - SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); - if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) { - resource.setAbstract(true); - } - } - } - resource.setContactId(resourceMetaData.getContactId()); - resource.setCreatorUserId(resourceMetaData.getContactId()); - - if (resourceMetaData.getVendorName() != null) { - resource.setVendorName(resourceMetaData.getVendorName()); - } - - if (resourceMetaData.getVendorRelease() != null) { - resource.setVendorRelease(resourceMetaData.getVendorRelease()); - } - - resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType())); - - } - - private void setConstantMetaData(Resource resource, boolean shouldBeCertified) { - String version; - LifecycleStateEnum state; - if(shouldBeCertified){ - version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION; - state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; - }else{ - version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; - state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; - } - resource.setVersion(version); - resource.setLifecycleState(state); - resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); - resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); - - } - - private Either validateOccurrences(List occurrensesList) { - - if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { - log.debug("Occurrenses list empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (occurrensesList.size() < 2) { - log.debug("Occurrenses list size not 2"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - Object minObj = occurrensesList.get(0); - Object maxObj = occurrensesList.get(1); - Integer minOccurrences = null; - Integer maxOccurrences = null; - if (minObj instanceof Integer) - minOccurrences = (Integer) minObj; - else { - log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - if (minOccurrences < 0) { - log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (maxObj instanceof String) { - if (maxObj.equals("UNBOUNDED")) { - return Either.left(true); - } else { - log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - } else { - if (maxObj instanceof Integer) - maxOccurrences = (Integer) maxObj; - else { - log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - - if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { - log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); - return Either.right(responseFormat); - } - } - - return Either.left(true); - - } - - public void init(ServletContext servletContext) { - if (this.servletContext == null) { - synchronized (this) { - if (this.servletContext == null) { - this.servletContext = servletContext; - responseFormatManager = ResponseFormatManager.getInstance(); - resourceBusinessLogic = getResourceBL(servletContext); - } - } - } - } - - public boolean isResourceExist(String resourceName) { - return resourceBusinessLogic.isResourceExist(resourceName); - } - - private ResourceBusinessLogic getResourceBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class); - return resourceBl; - } - - public ServletContext getServletContext() { - return servletContext; - } - - public IAuditingManager getAuditingManager() { - return auditingManager; - } - - public ResponseFormatManager getResponseFormatManager() { - return responseFormatManager; - } - - public void setResponseFormatManager(ResponseFormatManager responseFormatManager) { - this.responseFormatManager = responseFormatManager; - } - - public ResourceBusinessLogic getResourceBusinessLogic() { - return resourceBusinessLogic; - } - - public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) { - this.resourceBusinessLogic = resourceBusinessLogic; - } - - public Logger getLog() { - return log; - } - - public static void setLog(Logger log) { - ResourceImportManager.log = log; - } - - public IGraphLockOperation getGraphLockOperation() { - return graphLockOperation; - } - - public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { - this.graphLockOperation = graphLockOperation; - } - - public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; - } - - public void setAuditingManager(IAuditingManager auditingManager) { - this.auditingManager = auditingManager; - } + private ServletContext servletContext; + + @Autowired + private AuditingManager auditingManager; + + @Autowired + private ResourceBusinessLogic resourceBusinessLogic; + + @Autowired + private IGraphLockOperation graphLockOperation; + + @Autowired + protected ComponentsUtils componentsUtils; + + public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern + .compile("[\\w\\-\\_\\d\\:]+"); + @Autowired + protected CapabilityTypeOperation capabilityTypeOperation; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + private ResponseFormatManager responseFormatManager; + + private static final Logger log = LoggerFactory.getLogger(ResourceImportManager.class); + + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + public Either, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + lifecycleChangeInfo.setUserRemarks("certification on import"); + Function> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + } + + public Either, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + + LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); + lifecycleChangeInfo.setUserRemarks("certification on import"); + Function> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + } + + public Either, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function> validationFunction, + LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { + Resource resource = new Resource(); + ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); + Either, ResponseFormat> response = Either.left(responsePair); + + String latestCertifiedResourceId = null; + try { + boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty(); + setConstantMetaData(resource, shouldBeCertified); + setMetaDataFromJson(resourceMetaData, resource); + + Either validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); + if (validateResourceFromYaml.isRight()) { + ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); + return Either.right(validationErrorResponse); + + } + + Either isValidResource = validationFunction.apply(resource); + if (isValidResource.isLeft()) { + // The flag createNewVersion if false doesn't create new version + if (!createNewVersion) { + Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); + if (latestByName.isLeft()) { + return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource)); + } + } + + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested); + Either changeStateResponse; + if (response.isLeft()) { + resource = response.left().value().left; + + if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){ + Either, ResponseFormat> handleNodeTypeArtifactsRes = + resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); + if(handleNodeTypeArtifactsRes.isRight()){ + return Either.right(handleNodeTypeArtifactsRes.right().value()); + } + } + latestCertifiedResourceId = getLatestCertifiedResourceId(resource); + changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); + if (changeStateResponse.isRight()) { + response = Either.right(changeStateResponse.right().value()); + } else { + responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right); + response = Either.left(responsePair); + } + } + } else { + ResponseFormat validationErrorResponse = isValidResource.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, true); + response = Either.right(validationErrorResponse); + } + + } catch (RuntimeException e) { + ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e); + response = Either.right(exceptionResponse); + } finally { + if (latestCertifiedResourceId != null && needLock) { + log.debug("unlock resource {}", latestCertifiedResourceId); + graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); + } + } + + return response; + } + + private String getLatestCertifiedResourceId(Resource resource) { + Map allVersions = resource.getAllVersions(); + Double latestCertifiedVersion = 0.0; + if (allVersions != null) { + for (String version : allVersions.keySet()) { + Double dVersion = Double.valueOf(version); + if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) { + latestCertifiedVersion = dVersion; + } + } + return allVersions.get(String.valueOf(latestCertifiedVersion)); + } else { + return null; + } + } + + public void populateResourceMetadata(UploadResourceInfo resourceMetaData, Resource resource) { + if (resource != null && resourceMetaData != null) { + resource.setDescription(resourceMetaData.getDescription()); + resource.setTags(resourceMetaData.getTags()); + resource.setCategories(resourceMetaData.getCategories()); + resource.setContactId(resourceMetaData.getContactId()); + resource.setName(resourceMetaData.getName()); + resource.setIcon(resourceMetaData.getResourceIconPath()); + resource.setResourceVendorModelNumber(resourceMetaData.getResourceVendorModelNumber()); + resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType())); + if (resourceMetaData.getVendorName() != null) { + resource.setVendorName(resourceMetaData.getVendorName()); + } + if (resourceMetaData.getVendorRelease() != null) { + resource.setVendorRelease(resourceMetaData.getVendorRelease()); + } + } + } + + public Either, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) { + + Resource resource = new Resource(); + ImmutablePair responsePair = new ImmutablePair(resource, ActionStatus.CREATED); + Either, ResponseFormat> response = Either.left(responsePair); + + try { + setMetaDataFromJson(resourceMetaData, resource); + + Either validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource); + if (validateResourceFromYaml.isRight()) { + ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); + return Either.right(validationErrorResponse); + + } + + // currently import VF isn't supported. In future will be supported + // import VF only with CSER file!! + if (ResourceTypeEnum.VF.equals(resource.getResourceType())) { + log.debug("Now import VF isn't supported. It will be supported in future with CSER file only"); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE); + if (validateDerivedFromNotEmpty.isRight()) { + return Either.right(validateDerivedFromNotEmpty.right().value()); + } + + Either validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); + + if (validatePropertiesTypes.isLeft()) { + response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false); + } else { + ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value(); + auditErrorImport(resourceMetaData, creator, validationErrorResponse, false); + response = Either.right(validationErrorResponse); + } + + } catch (RuntimeException e) { + ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e); + response = Either.right(exceptionResponse); + } + + return response; + + } + + Either populateResourceFromYaml(String resourceYml, Resource resource) { + @SuppressWarnings("unchecked") + Either eitherResult = Either.left(true); + Map toscaJsonAll = (Map) new Yaml().load(resourceYml); + Map toscaJson = toscaJsonAll; + + // Checks if exist and builds the node_types map + if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) { + toscaJson = new HashMap(); + toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName())); + } + // Derived From + Either setDerivedFrom = setDerivedFrom(toscaJson, resource); + if (setDerivedFrom.isRight()) { + return Either.right(setDerivedFrom.right().value()); + } + Resource parentResource = setDerivedFrom.left().value(); + if(StringUtils.isEmpty(resource.getToscaResourceName())) { + setToscaResourceName(toscaJson, resource); + } + setAttributes(toscaJson, resource); + eitherResult = setCapabilities(toscaJson, resource, parentResource); + if (eitherResult.isRight()) { + return eitherResult; + } + eitherResult = setProperties(toscaJson, resource); + if (eitherResult.isRight()) { + return eitherResult; + } + eitherResult = setRequirements(toscaJson, resource, parentResource); + if (eitherResult.isRight()) { + return eitherResult; + } + setInterfaceLifecycle(toscaJson, resource); + + return eitherResult; + } + + private void setToscaResourceName(Map toscaJson, Resource resource) { + Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) { + String toscaResourceName = toscaElement.left().value().keySet().iterator().next(); + resource.setToscaResourceName(toscaResourceName); + } + } + + private void setInterfaceLifecycle(Map toscaJson, Resource resource) { + Either, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES); + if (toscaInterfaces.isLeft()) { + Map jsonInterfaces = toscaInterfaces.left().value(); + Map moduleInterfaces = new HashMap(); + Iterator> interfacesNameValue = jsonInterfaces.entrySet().iterator(); + while (interfacesNameValue.hasNext()) { + Entry interfaceNameValue = interfacesNameValue.next(); + Either eitherInterface = createModuleInterface(interfaceNameValue.getValue()); + if (eitherInterface.isRight()) { + log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); + } else { + moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value()); + } + + } + if (moduleInterfaces.size() > 0) { + resource.setInterfaces(moduleInterfaces); + } + } + } + + private Either createModuleInterface(Object interfaceJson) { + InterfaceDefinition interf = new InterfaceDefinition(); + Either result = Either.left(interf); + + try { + if (interfaceJson instanceof String) { + String requirementJsonString = (String) interfaceJson; + interf.setType(requirementJsonString); + } else if (interfaceJson instanceof Map) { + Map requirementJsonMap = (Map) interfaceJson; + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()); + interf.setType(type); + interf.setUniqueId(type.toLowerCase()); + } + } else { + result = Either.right(ResultStatusEnum.GENERAL_ERROR); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); + log.debug("error when creating interface, message:{}", e.getMessage(), e); + result = Either.right(ResultStatusEnum.GENERAL_ERROR); + } + + return result; + } + + private Either setRequirements(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null + Either eitherResult = Either.left(true); + Either, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS); + if (toscaRequirements.isLeft()) { + List jsonRequirements = toscaRequirements.left().value(); + Map> moduleRequirements = new HashMap>(); + // Checking for name duplication + Set reqNames = new HashSet<>(); + // Getting flattened list of capabilities of parent node - cap name + // to cap type + Either, ResponseFormat> reqName2Type = getReqName2Type(parentResource); + if (reqName2Type.isRight()) { + ResponseFormat responseFormat = reqName2Type.right().value(); + log.debug("Error during setting requirements of imported resource: {}", responseFormat); + return Either.right(responseFormat); + } + Map reqName2TypeMap = reqName2Type.left().value(); + for (Object jsonRequirementObj : jsonRequirements) { + // Requirement + Map requirementJsonWrapper = (Map) jsonRequirementObj; + String requirementName = requirementJsonWrapper.keySet().iterator().next(); + String reqNameLowerCase = requirementName.toLowerCase(); + if (reqNames.contains(reqNameLowerCase)) { + log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase)); + } + reqNames.add(reqNameLowerCase); + Either eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName)); + if (eitherRequirement.isRight()) { + log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName()); + return Either.right(eitherRequirement.right().value()); + } + RequirementDefinition requirementDef = eitherRequirement.left().value(); + requirementDef.setName(requirementName); + if (moduleRequirements.containsKey(requirementDef.getCapability())) { + moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); + } else { + List list = new ArrayList(); + list.add(requirementDef); + moduleRequirements.put(requirementDef.getCapability(), list); + } + + // Validating against req/cap of "derived from" node + Either validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName()); + if (validateVsParentCap.isRight()) { + return Either.right(validateVsParentCap.right().value()); + } + if (!validateVsParentCap.left().value()) { + log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName()); + return Either.right(responseFormat); + } + } + if (moduleRequirements.size() > 0) { + resource.setRequirements(moduleRequirements); + } + + } + return eitherResult; + + } + + private Either createRequirementFromImportFile(Object requirementJson) { + RequirementDefinition requirement = new RequirementDefinition(); + Either result = Either.left(requirement); + + try { + if (requirementJson instanceof String) { + String requirementJsonString = (String) requirementJson; + requirement.setCapability(requirementJsonString); + } else if (requirementJson instanceof Map) { + Map requirementJsonMap = (Map) requirementJson; + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) { + requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName())); + } + + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) { + requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName())); + } + + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { + requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName())); + } + if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); + Either validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); + if (validateAndSetOccurrencesStatus.isRight()) { + result = Either.right(validateAndSetOccurrencesStatus.right().value()); + return result; + } + if (validateAndSetOccurrencesStatus.left().value()) { + requirement.setMinOccurrences(occurrencesList.get(0).toString()); + requirement.setMaxOccurrences(occurrencesList.get(1).toString()); + } + + } + } else { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement"); + log.debug("error when creating requirement, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private Either setProperties(Map toscaJson, Resource resource) { + Map reducedToscaJson = new HashMap<>(toscaJson); + ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); + Either result = Either.left(true); + Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); + if (properties.isLeft()) { + List propertiesList = new ArrayList<>(); + Map value = properties.left().value(); + if (value != null) { + for (Entry entry : value.entrySet()) { + String name = entry.getKey(); + if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ + log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); + } + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + propertiesList.add(propertyDefinition); + } + } + resource.setProperties(propertiesList); + } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); + } + return result; + } + + private ResultStatusEnum setAttributes(Map toscaJson, Resource resource) { + ResultStatusEnum result = ResultStatusEnum.OK; + Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); + if (attributes.isLeft()) { + List attributeList = new ArrayList<>(); + Map value = attributes.left().value(); + if (value != null) { + for (Entry entry : value.entrySet()) { + String name = entry.getKey(); + PropertyDefinition attributeDef = entry.getValue(); + attributeDef.setName(name); + attributeList.add(attributeDef); + } + } + resource.setAttributes(attributeList); + } else { + result = attributes.right().value(); + } + return result; + } + + private Either setDerivedFrom(Map toscaJson, Resource resource) { + Either toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM); + Resource derivedFromResource = null; + if (toscaDerivedFromElement.isLeft()) { + String derivedFrom = toscaDerivedFromElement.left().value(); + log.debug("Derived from TOSCA name is {}", derivedFrom); + resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom })); + Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); + + if (latestByToscaResourceName.isRight()) { + StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); + if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) { + operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND; + } + log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); + ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); + BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); + return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom)); + } + derivedFromResource = latestByToscaResourceName.left().value(); + } + return Either.left(derivedFromResource); + } + + private Either setCapabilities(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null + Either eitherResult = Either.left(true); + Either, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES); + if (toscaCapabilities.isLeft()) { + Map jsonCapabilities = toscaCapabilities.left().value(); + Map> moduleCapabilities = new HashMap>(); + Iterator> capabilitiesNameValue = jsonCapabilities.entrySet().iterator(); + Set capNames = new HashSet<>(); + // Getting flattened list of capabilities of parent node - cap name + // to cap type + Either, ResponseFormat> capName2Type = getCapName2Type(parentResource); + if (capName2Type.isRight()) { + ResponseFormat responseFormat = capName2Type.right().value(); + log.debug("Error during setting capabilities of imported resource: {}", responseFormat); + return Either.right(responseFormat); + } + Map capName2TypeMap = capName2Type.left().value(); + while (capabilitiesNameValue.hasNext()) { + Entry capabilityNameValue = capabilitiesNameValue.next(); + + // Validating that no req/cap duplicates exist in imported YAML + String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); + if (capNames.contains(capNameLowerCase)) { + log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase)); + } + capNames.add(capNameLowerCase); + + Either eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue()); + if (eitherCapability.isRight()) { + log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName()); + return Either.right(eitherCapability.right().value()); + } + + CapabilityDefinition capabilityDef = eitherCapability.left().value(); + capabilityDef.setName(capabilityNameValue.getKey()); + if (moduleCapabilities.containsKey(capabilityDef.getType())) { + moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); + } else { + List list = new ArrayList(); + list.add(capabilityDef); + moduleCapabilities.put(capabilityDef.getType(), list); + } + + // Validating against req/cap of "derived from" node + Either validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName()); + if (validateVsParentCap.isRight()) { + return Either.right(validateVsParentCap.right().value()); + } + if (!validateVsParentCap.left().value()) { + // Here parentResource is for sure not null, so it's + // null-safe + log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName()); + return Either.right(responseFormat); + } + } + if (moduleCapabilities.size() > 0) { + resource.setCapabilities(moduleCapabilities); + } + } + + return eitherResult; + + } + + private Either, ResponseFormat> getCapName2Type(Resource parentResource) { + Map capName2type = new HashMap<>(); + if (parentResource != null) { + Map> capabilities = parentResource.getCapabilities(); + if (capabilities != null) { + for (List capDefinitions : capabilities.values()) { + for (CapabilityDefinition capDefinition : capDefinitions) { + String nameLowerCase = capDefinition.getName().toLowerCase(); + if (capName2type.get(nameLowerCase) != null) { + String parentResourceName = parentResource.getName(); + log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); + BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + capName2type.put(nameLowerCase, capDefinition.getType()); + } + } + } + } + return Either.left(capName2type); + } + + private Either, ResponseFormat> getReqName2Type(Resource parentResource) { + Map reqName2type = new HashMap<>(); + if (parentResource != null) { + Map> requirements = parentResource.getRequirements(); + if (requirements != null) { + for (List reqDefinitions : requirements.values()) { + for (RequirementDefinition reqDefinition : reqDefinitions) { + String nameLowerCase = reqDefinition.getName().toLowerCase(); + if (reqName2type.get(nameLowerCase) != null) { + String parentResourceName = parentResource.getName(); + log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); + BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + reqName2type.put(nameLowerCase, reqDefinition.getCapability()); + } + } + } + } + return Either.left(reqName2type); + } + + private Either validateCapNameVsDerived(Map parentCapName2Type, String childCapabilityType, String reqCapName) { + String capNameLowerCase = reqCapName.toLowerCase(); + log.trace("Validating capability {} vs parent resource", capNameLowerCase); + String parentCapType = parentCapName2Type.get(capNameLowerCase); + if (parentCapType != null) { + if (childCapabilityType.equals(parentCapType)) { + log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); + return Either.left(true); + } + Either capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); + if (capabilityTypeDerivedFrom.isRight()) { + log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value())); + return Either.right(responseFormat); + } + return Either.left(capabilityTypeDerivedFrom.left().value()); + } + return Either.left(true); + } + + private Either createCapabilityFromImportFile(Object capabilityJson) { + + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + Either result = Either.left(capabilityDefinition); + + try { + if (capabilityJson instanceof String) { + String capabilityJsonString = (String) capabilityJson; + capabilityDefinition.setType(capabilityJsonString); + } else if (capabilityJson instanceof Map) { + Map capabilityJsonMap = (Map) capabilityJson; + // Type + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) { + capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName())); + } + // ValidSourceTypes + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { + capabilityDefinition.setValidSourceTypes((List) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())); + } + // ValidSourceTypes + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) { + capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); + } + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) { + List occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName()); + Either validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList); + if (validateAndSetOccurrencesStatus.isRight()) { + result = Either.right(validateAndSetOccurrencesStatus.right().value()); + return result; + } + if (validateAndSetOccurrencesStatus.left().value()) { + capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); + capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); + } + } + if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) { + + Either, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); + if (propertiesRes.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND)); + return result; + } else { + propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); + List capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); + capabilityDefinition.setProperties(capabilityProperties); + } + } + } else if (!(capabilityJson instanceof List)) { + + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability"); + log.debug("error when creating capability, message:{}", e.getMessage(), e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML)); + } + + return result; + } + + private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { + String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : ""; + BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName); + + log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e); + ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); + auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative); + return errorResponseWrapper; + } + + private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { +// EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus()); +// String message = ""; +// if (errorResponseWrapper.getMessageId() != null) { +// message = errorResponseWrapper.getMessageId() + ": "; +// } +// message += errorResponseWrapper.getFormattedMessage(); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); + + String version, lifeCycleState; + if (isNormative) { + version = Constants.FIRST_CERTIFIED_VERSION_VERSION; + lifeCycleState = LifecycleStateEnum.CERTIFIED.name(); + } else { + version = ""; + lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); + + } +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState); +// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); +// getAuditingManager().auditEvent(auditingFields); + + + String message = ""; + if (errorResponseWrapper.getMessageId() != null) { + message = errorResponseWrapper.getMessageId() + ": "; + } + message += errorResponseWrapper.getFormattedMessage(); + + + + AuditEventFactory factory = new AuditImportResourceAdminEventFactory( + CommonAuditData.newBuilder() + .status(errorResponseWrapper.getStatus()) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + ResourceAuditData.newBuilder() + .state(lifeCycleState) + .version(version) + .build(), + ResourceAuditData.newBuilder() + .state("") + .version("") + .build(), + ComponentTypeEnum.RESOURCE.getValue(), resourceMetaData.getName(), "", user, ""); + getAuditingManager().auditEvent(factory); + + } + + private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) { + this.populateResourceMetadata(resourceMetaData, resource); + resource.setCreatorUserId(resourceMetaData.getContactId()); + List categories = resourceMetaData.getCategories(); + calculateResourceIsAbstract(resource, categories); + } + + private void calculateResourceIsAbstract(Resource resource, List categories) { + if (categories != null && !categories.isEmpty()) { + CategoryDefinition categoryDef = categories.get(0); + resource.setAbstract(false); + if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) { + SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); + if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) { + resource.setAbstract(true); + } + } + } + } + + private void setConstantMetaData(Resource resource, boolean shouldBeCertified) { + String version; + LifecycleStateEnum state; + if(shouldBeCertified){ + version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; + }else{ + version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; + state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; + } + resource.setVersion(version); + resource.setLifecycleState(state); + resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + resource.setVendorName(ImportUtils.Constants.VENDOR_NAME); + resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE); + + } + + private Either validateOccurrences(List occurrensesList) { + + if (!ValidationUtils.validateListNotEmpty(occurrensesList)) { + log.debug("Occurrenses list empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (occurrensesList.size() < 2) { + log.debug("Occurrenses list size not 2"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + Object minObj = occurrensesList.get(0); + Object maxObj = occurrensesList.get(1); + Integer minOccurrences = null; + Integer maxOccurrences = null; + if (minObj instanceof Integer) + minOccurrences = (Integer) minObj; + else { + log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + if (minOccurrences < 0) { + log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (maxObj instanceof String) { + if ("UNBOUNDED".equals(maxObj)) { + return Either.left(true); + } else { + log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + } else { + if (maxObj instanceof Integer) + maxOccurrences = (Integer) maxObj; + else { + log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + + if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { + log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES); + return Either.right(responseFormat); + } + } + + return Either.left(true); + + } + + public synchronized void init(ServletContext servletContext) { + if (this.servletContext == null) { + this.servletContext = servletContext; + responseFormatManager = ResponseFormatManager.getInstance(); + resourceBusinessLogic = getResourceBL(servletContext); + } + } + + public boolean isResourceExist(String resourceName) { + return resourceBusinessLogic.isResourceExist(resourceName); + } + + private ResourceBusinessLogic getResourceBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class); + return resourceBl; + } + + public ServletContext getServletContext() { + return servletContext; + } + + public AuditingManager getAuditingManager() { + return auditingManager; + } + + public ResponseFormatManager getResponseFormatManager() { + return responseFormatManager; + } + + public void setResponseFormatManager(ResponseFormatManager responseFormatManager) { + this.responseFormatManager = responseFormatManager; + } + + public ResourceBusinessLogic getResourceBusinessLogic() { + return resourceBusinessLogic; + } + + public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) { + this.resourceBusinessLogic = resourceBusinessLogic; + } + + public Logger getLog() { + return log; + } + + public IGraphLockOperation getGraphLockOperation() { + return graphLockOperation; + } + + public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { + this.graphLockOperation = graphLockOperation; + } + + public void setServletContext(ServletContext servletContext) { + this.servletContext = servletContext; + } + + public void setAuditingManager(AuditingManager auditingManager) { + this.auditingManager = auditingManager; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java index 136121484d..a6344929a5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java @@ -34,44 +34,44 @@ import org.slf4j.LoggerFactory; public class ResponseFormatManager { - private volatile static ResponseFormatManager instance; - private static ConfigurationManager configurationManager; - private static Logger log = LoggerFactory.getLogger(ResponseFormatManager.class.getName()); + private volatile static ResponseFormatManager instance; + private static ConfigurationManager configurationManager; + private static final Logger log = LoggerFactory.getLogger(ResponseFormatManager.class); - public static ResponseFormatManager getInstance() { - if (instance == null) { + public static ResponseFormatManager getInstance() { + if (instance == null) { - instance = init(); - } - return instance; - } + instance = init(); + } + return instance; + } - private static synchronized ResponseFormatManager init() { - if (instance == null) { - instance = new ResponseFormatManager(); - configurationManager = ConfigurationManager.getConfigurationManager(); - } - return instance; - } + private static synchronized ResponseFormatManager init() { + if (instance == null) { + instance = new ResponseFormatManager(); + configurationManager = ConfigurationManager.getConfigurationManager(); + } + return instance; + } - public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) { - ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration(); - ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name()); - if (errorInfo == null) { - log.debug("failed to locate {} in error configuration", responseEnum.name()); - errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name()); - } - ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode()); - String errorMessage = errorInfo.getMessage(); - String errorMessageId = errorInfo.getMessageId(); - ErrorInfoType errorInfoType = errorInfo.getErrorInfoType(); - if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) { - errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) { - errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables)); - } else if (errorInfoType.equals(ErrorInfoType.OK)) { - errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables)); - } - return errorResponseWrapper; - } + public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) { + ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration(); + ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name()); + if (errorInfo == null) { + log.debug("failed to locate {} in error configuration", responseEnum); + errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name()); + } + ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode()); + String errorMessage = errorInfo.getMessage(); + String errorMessageId = errorInfo.getMessageId(); + ErrorInfoType errorInfoType = errorInfo.getErrorInfoType(); + if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) { + errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables)); + } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) { + errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables)); + } else if (errorInfoType.equals(ErrorInfoType.OK)) { + errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables)); + } + return errorResponseWrapper; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 23852c30a2..14db1408b7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +20,33 @@ package org.openecomp.sdc.be.components.impl; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - +import com.google.common.base.Strings; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; import org.openecomp.sdc.be.components.distribution.engine.INotificationData; import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datamodel.ServiceRelations; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -67,6 +61,8 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -79,12 +75,12 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; import org.openecomp.sdc.common.util.GeneralUtility; @@ -96,1997 +92,2213 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("serviceBusinessLogic") public class ServiceBusinessLogic extends ComponentBusinessLogic { - private static final String STATUS_SUCCESS_200 = "200"; - - private static final String STATUS_DEPLOYED = "DEPLOYED"; - - @Autowired - private IElementOperation elementDao; - - @Autowired - private IDistributionEngine distributionEngine; - - // @Autowired - // private AuditingDao auditingDao; - - @Autowired - private AuditCassandraDao auditCassandraDao; - - @Autowired - private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic; - - @Autowired - private GroupBusinessLogic groupBusinessLogic; - - @Autowired - private ICacheMangerOperation cacheManagerOperation; - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName()); - private static final String INITIAL_VERSION = "0.1"; - - public ServiceBusinessLogic() { - log.debug("ServiceBusinessLogic started"); - } - - public Either changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) { - - Either resp = validateUserExists(user.getUserId(), "change Service Distribution State", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.debug("check request state"); - Either validateEnum = validateTransitionEnum(state, user); - if (validateEnum.isRight()) { - return Either.right(validateEnum.right().value()); - } - DistributionTransitionEnum distributionTransition = validateEnum.left().value(); - AuditingActionEnum auditAction = (distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT); - Either commentResponse = validateComment(commentObj, user, auditAction); - if (commentResponse.isRight()) { - return Either.right(commentResponse.right().value()); - } - String comment = commentResponse.left().value(); - - Either validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment); - if (validateService.isRight()) { - return Either.right(validateService.right().value()); - } - Service service = validateService.left().value(); - DistributionStatusEnum initState = service.getDistributionStatus(); - - Either validateUser = validateUserDistributionChange(user, service, auditAction, comment); - if (validateUser.isRight()) { - return Either.right(validateUser.right().value()); - } - user = validateUser.left().value(); - - // lock resource - /* - * StorageOperationStatus lockResult = graphLockOperation.lockComponent(serviceId, NodeTypeEnum.Service); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. - * BeFailedLockObjectError, "ChangeServiceDistributionState"); log.debug("Failed to lock service {} error - {}", serviceId, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, - * service.getVersion(), service.getServiceName()); - * - * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); } - */ - Either lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - - try { - - DistributionStatusEnum newState; - if (distributionTransition == DistributionTransitionEnum.APPROVE) { - newState = DistributionStatusEnum.DISTRIBUTION_APPROVED; - } else { - newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; - } - Either result = toscaOperationFacade.updateDistributionStatus(service, user, newState); - if (result.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); - log.debug("service {} is change destribuation status failed", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - Service updatedService = result.left().value(); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, updatedService.getDistributionStatus().name()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, initState.name()); - createAudit(user, auditAction, comment, updatedService, responseFormat, auditingFields); - return Either.left(result.left().value()); - - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - - } - - public Either>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { - Either resp = validateUserExists(userId, "get Component Audit Records", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either>, ActionStatus> result; - try { - - // Certified Version - if (componentVersion.endsWith(".0")) { - Either, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID); - if (eitherAuditingForCertified.isLeft()) { - result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value())); - } else { - result = Either.right(eitherAuditingForCertified.right().value()); - } - } - // Uncertified Version - else { - result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion); - } - } catch (Exception e) { - log.debug("get Audit Records failed with exception {}", e); - result = Either.right(ActionStatus.GENERAL_ERROR); - } - - if (result.isRight()) { - return Either.right(componentsUtils.getResponseFormat(result.right().value())); - } else { - return Either.left(result.left().value()); - } - - } - - private Either>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) { - // First Query - Either, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); - - if (eitherprevVerAudit.isRight()) { - return Either.right(eitherprevVerAudit.right().value()); - } - - // Second Query - Either, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); - if (eitherCurrVerAudit.isRight()) { - return Either.right(eitherCurrVerAudit.right().value()); - } - - List> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value()); - List> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value()); - - List> duplicateElements = new ArrayList>(); - duplicateElements.addAll(prevVerAuditList); - duplicateElements.retainAll(currVerAuditList); - - List> joinedNonDuplicatedList = new ArrayList>(); - joinedNonDuplicatedList.addAll(prevVerAuditList); - joinedNonDuplicatedList.removeAll(duplicateElements); - joinedNonDuplicatedList.addAll(currVerAuditList); - - return Either.left(joinedNonDuplicatedList); - } - - private List> getAuditingFieldsList(List prevVerAuditList) { - - List> prevVerAudit = new ArrayList>(); - for (AuditingGenericEvent auditEvent : prevVerAuditList) { - auditEvent.fillFields(); - prevVerAudit.add(auditEvent.getFields()); - } - return prevVerAudit; - } - - /** - * createService - * - * @param service - * - Service - * @param user - * - modifier data (userId) - * @return Either - */ - public Either createService(Service service, User user) { - - // get user details - Either eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either validateRes = validateUserRole(user, service, new ArrayList(), AuditingActionEnum.CREATE_RESOURCE, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - service.setCreatorUserId(user.getUserId()); - - // warn on overridden fields - checkFieldsForOverideAttampt(service); - // enrich object - log.debug("enrich service with version and state"); - service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - service.setVersion(INITIAL_VERSION); - service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); - service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); - - Either createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); - if (createServiceResponse.isRight()) { - return createServiceResponse; - } - return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); - } - - private void checkFieldsForOverideAttampt(Service service) { - checkComponentFieldsForOverrideAttempt(service); - if ((service.getDistributionStatus() != null)) { - log.info("Distribution Status cannot be defined by user. This field will be overridden by the application"); - } - } - - private Either createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) { - log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - Either lockResult = lockComponentByName(service.getSystemName(), service, "Create Service"); - if (lockResult.isRight()) { - ResponseFormat responseFormat = lockResult.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult); - - try { - - createMandatoryArtifactsData(service, user); - createServiceApiArtifactsData(service, user); - setToscaArtifactsPlaceHolders(service, user); - Either genericServiceEither = fetchAndSetDerivedFromGenericType(service); - if (genericServiceEither.isRight()) - return Either.right(genericServiceEither.right().value()); - - generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); - - Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); - - // service created successfully!!! - if (dataModelResponse.isLeft()) { - log.debug("Service created successfully!!!"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - ASDCKpiApi.countCreatedServicesKPI(); - return Either.left(dataModelResponse.left().value()); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE); - log.debug("audit before sending response"); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - - } finally { - graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service); - } - } - - @SuppressWarnings("unchecked") - private void createServiceApiArtifactsData(Service service, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String serviceUniqueId = - // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion()); - String serviceUniqueId = service.getUniqueId(); - Map artifactMap = service.getServiceApiArtifacts(); - if (artifactMap == null) - artifactMap = new HashMap(); - - Map serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts(); - List exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); - - List categories = service.getCategories(); - boolean isCreateArtifact = true; - if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { - for (String exlude : exludeServiceCategory) { - if (exlude.equalsIgnoreCase(categories.get(0).getName())) { - isCreateArtifact = false; - break; - } - } - - } - - if (serviceApiArtifacts != null && isCreateArtifact) { - Set keys = serviceApiArtifacts.keySet(); - for (String serviceApiArtifactName : keys) { - Map artifactInfoMap = (Map) serviceApiArtifacts.get(serviceApiArtifactName); - ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true); - artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - } - - service.setServiceApiArtifacts(artifactMap); - } - } - - private Either validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { - - Either validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum); - if (validationResponse.isRight()) { - return Either.right(validationResponse.right().value()); - } - service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - service.setContactId(service.getContactId().toLowerCase()); - - // Generate invariant UUID - must be here and not in operation since it - // should stay constant during clone - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - service.setInvariantUUID(invariantUUID); - - return Either.left(service); - } - - private Either validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { - Either componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum); - if (componentsFieldsValidation.isRight()) { - return componentsFieldsValidation; - } - - log.debug("validate service name uniqueness"); - Either serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum); - if (serviceNameUniquenessValidation.isRight()) { - return serviceNameUniquenessValidation; - } - - log.debug("validate category"); - Either categoryValidation = validateServiceCategory(user, service, actionEnum); - if (categoryValidation.isRight()) { - return categoryValidation; - } - - // validate project name (ProjectCode) - mandatory in service - log.debug("validate projectName"); - Either projectCodeValidation = validateProjectCode(user, service, actionEnum); - if (projectCodeValidation.isRight()) { - return projectCodeValidation; - } - - log.debug("validate service type"); - Either serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum); - if (serviceTypeValidation.isRight()) { - return serviceTypeValidation; - } - - log.debug("validate service role"); - Either serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum); - if (serviceRoleValidation.isRight()) { - return serviceRoleValidation; - } - - return Either.left(true); - - } - - private Either validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) { - log.debug("validate Service category"); - - if (service.getCategories() == null || service.getCategories().size() == 0) { - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - componentsUtils.auditComponentAdmin(errorResponse, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - - Either validatCategory = validateServiceCategory(service.getCategories()); - if (validatCategory.isRight()) { - ResponseFormat responseFormat = validatCategory.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - return Either.left(true); - } - - public Either, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { - - Either resp = validateUserExists(userId, "validate Service Name Exists", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); - - // DE242223 - titanDao.commit(); - - if (dataModelResponse.isLeft()) { - Map result = new HashMap<>(); - result.put("isValid", dataModelResponse.left().value()); - log.debug("validation was successfully performed."); - return Either.left(result); - } - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); - - return Either.right(responseFormat); - } - - public void setElementDao(IElementOperation elementDao) { - this.elementDao = elementDao; - } - - public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { - this.auditCassandraDao = auditingDao; - } - - /* - * public void setUserAdmin(UserAdminBuisinessLogic userAdmin) { this.userAdmin = userAdmin; } - * - * public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; } - * - * public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; } - */ - - public ArtifactsBusinessLogic getArtifactBl() { - return artifactsBusinessLogic; - } - - public void setArtifactBl(ArtifactsBusinessLogic artifactBl) { - this.artifactsBusinessLogic = artifactBl; - } - - public Either updateServiceMetadata(String serviceId, Service serviceUpdate, User user) { - Either eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - Either validateRes = validateUserRole(user, serviceUpdate, new ArrayList(), null, null); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - - Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); - } - - Service currentService = storageStatus.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) { - log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - - Either validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate); - if (validationRsponse.isRight()) { - log.info("service update metadata: validations field."); - return validationRsponse; - } - Service serviceToUpdate = validationRsponse.left().value(); - // lock resource - - Either lockResult = lockComponent(serviceId, currentService, "Update Service Metadata"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); - if (updateResponse.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); - log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - return Either.left(updateResponse.left().value()); - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - private Either validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) { - - boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion()); - Either response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String creatorUserIdUpdated = serviceUpdate.getCreatorUserId(); - String creatorUserIdCurrent = currentService.getCreatorUserId(); - if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) { - log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated); - } - - String creatorFullNameUpdated = serviceUpdate.getCreatorFullName(); - String creatorFullNameCurrent = currentService.getCreatorFullName(); - if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) { - log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated); - } - - String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId(); - String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId(); - if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) { - log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated); - } - - String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName(); - String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName(); - if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) { - log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated); - } - - response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus(); - DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus(); - if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals((distributionStatusCurrent != null ? distributionStatusCurrent.name() : null))) { - log.info("update srvice: recived request to update distributionStatus to {} the field is not updatable ignoring.", distributionStatusUpdated); - } - - if (serviceUpdate.getProjectCode() != null) { - response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - } - - response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - Long creationDateUpdated = serviceUpdate.getCreationDate(); - Long creationDateCurrent = currentService.getCreationDate(); - if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) { - log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated); - } - - String versionUpdated = serviceUpdate.getVersion(); - String versionCurrent = currentService.getVersion(); - if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { - log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); - } - - response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateContactId(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate(); - Long lastUpdateDateCurrent = currentService.getLastUpdateDate(); - if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) { - log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated); - } - - LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState(); - LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState(); - if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) { - log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated); - } - - Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion(); - Boolean isHighestVersionCurrent = currentService.isHighestVersion(); - if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) { - log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated); - } - - String uuidUpdated = serviceUpdate.getUUID(); - String uuidCurrent = currentService.getUUID(); - if (!uuidCurrent.equals(uuidUpdated)) { - log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); - } - - response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null); - if (response.isRight()) { - ResponseFormat errorResponse = response.right().value(); - return Either.right(errorResponse); - } - - String currentInvariantUuid = currentService.getInvariantUUID(); - String updatedInvariantUuid = serviceUpdate.getInvariantUUID(); - - if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { - log.warn("Product invariant UUID is automatically set and cannot be updated"); - serviceUpdate.setInvariantUUID(currentInvariantUuid); - } - validateAndUpdateEcompNaming(currentService, serviceUpdate); - - currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); - - return Either.left(currentService); - - } - - private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) { - Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming(); - Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming(); - if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) { - currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate); - } - String namingPolicyUpd = serviceUpdate.getNamingPolicy(); - if (!currentService.isEcompGeneratedNaming()) { - if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) { - log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false"); - currentService.setNamingPolicy(""); - } else { - currentService.setNamingPolicy(namingPolicyUpd); - } - }else{ - currentService.setNamingPolicy(namingPolicyUpd); - } - } - - private Either validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { - String contactIdUpdated = serviceUpdate.getContactId(); - String contactIdCurrent = currentService.getContactId(); - if (!contactIdCurrent.equals(contactIdUpdated)) { - Either validatContactId = validateContactId(user, serviceUpdate, audatingAction); - if (validatContactId.isRight()) { - ResponseFormat errorRespons = validatContactId.right().value(); - return Either.right(errorRespons); - } - currentService.setContactId(contactIdUpdated.toLowerCase()); - } - return Either.left(true); - } - - private Either validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - List tagsUpdated = serviceUpdate.getTags(); - List tagsCurrent = currentService.getTags(); - if (tagsUpdated == null || tagsUpdated.isEmpty()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS); - componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, "", "", audatingAction, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - - if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { - Either validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction); - if (validatResponse.isRight()) { - ResponseFormat errorRespons = validatResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setTags(tagsUpdated); - } - return Either.left(true); - } - - private Either validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - String descriptionUpdated = serviceUpdate.getDescription(); - String descriptionCurrent = currentService.getDescription(); - if (!descriptionCurrent.equals(descriptionUpdated)) { - Either validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction); - if (validateDescriptionResponse.isRight()) { - ResponseFormat errorRespons = validateDescriptionResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setDescription(serviceUpdate.getDescription()); - } - return Either.left(true); - } - - private Either validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { - String projectCodeUpdated = serviceUpdate.getProjectCode(); - String projectCodeCurrent = currentService.getProjectCode(); - if (!projectCodeCurrent.equals(projectCodeUpdated)) { - - Either validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); - if (validatProjectCodeResponse.isRight()) { - ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setProjectCode(projectCodeUpdated); - - } - return Either.left(true); - } - - private Either validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - String iconUpdated = serviceUpdate.getIcon(); - String iconCurrent = currentService.getIcon(); - if (!iconCurrent.equals(iconUpdated)) { - if (!hasBeenCertified) { - Either validatIconResponse = validateIcon(user, serviceUpdate, audatingAction); - if (validatIconResponse.isRight()) { - ResponseFormat errorRespons = validatIconResponse.right().value(); - return Either.right(errorRespons); - } - currentService.setIcon(iconUpdated); - } else { - log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) { - String serviceNameUpdated = serviceUpdate.getName(); - String serviceNameCurrent = currentService.getName(); - if (!serviceNameCurrent.equals(serviceNameUpdated)) { - if (!hasBeenCertified) { - Either validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction); - if (validatServiceNameResponse.isRight()) { - ResponseFormat errorRespons = validatServiceNameResponse.right().value(); - return Either.right(errorRespons); - } - - Either serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction); - if (serviceNameUniquenessValidation.isRight()) { - return serviceNameUniquenessValidation; - } - currentService.setName(serviceNameUpdated); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); - currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated)); - - } else { - log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - } - - private Either validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { - String updatedServiceType = updatedService.getServiceType(); - String currentServiceType = currentService.getServiceType(); - if (!currentServiceType.equals(updatedServiceType)) { - Either validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction); - if (validateServiceType.isRight()) { - ResponseFormat errorResponse = validateServiceType.right().value(); - componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - currentService.setServiceType(updatedServiceType); - } - return Either.left(true); - } - - protected Either validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - String serviceType = ((Service)component).getServiceType(); - if (serviceType != null){ - serviceType = cleanUpText(serviceType); - Either validateServiceType = validateServiceType(serviceType); - if (validateServiceType.isRight()) { - ResponseFormat responseFormat = validateServiceType.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } else { - return Either.left(false); - } - } - - - private Either validateServiceType(String serviceType) { - if (serviceType.equals("")){ - return Either.left(true); - } else { - if (!ValidationUtils.validateServiceTypeLength(serviceType)) { - log.info("service type exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateIsEnglish(serviceType)) { - log.info("service type is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - private Either validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { - String updatedServiceRole = updatedService.getServiceRole(); - String currentServiceRole = currentService.getServiceRole(); - if (!currentServiceRole.equals(updatedServiceRole)) { - Either validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction); - if (validateServiceRole.isRight()) { - ResponseFormat errorResponse = validateServiceRole.right().value(); - componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE); - return Either.right(errorResponse); - } - currentService.setServiceRole(updatedServiceRole); - } - return Either.left(true); - } - - protected Either validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { - String serviceRole = ((Service)component).getServiceRole(); - if (serviceRole != null){ - serviceRole = cleanUpText(serviceRole); - - Either validateServiceRole = validateServiceRole(serviceRole); - if (validateServiceRole.isRight()) { - ResponseFormat responseFormat = validateServiceRole.right().value(); - componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE); - return Either.right(responseFormat); - } - return Either.left(true); - } else { - return Either.left(false); - } - } - - - private Either validateServiceRole(String serviceRole) { - if (serviceRole.equals("")){ - return Either.left(true); - } else { - if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { - log.info("service role exceeds limit."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH); - return Either.right(errorResponse); - } - - if (!ValidationUtils.validateIsEnglish(serviceRole)) { - log.info("service role is not valid."); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE); - return Either.right(errorResponse); - } - return Either.left(true); - } - } - - - - private Either validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { - List categoryUpdated = serviceUpdate.getCategories(); - List categoryCurrent = currentService.getCategories(); - Either validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction); - if (validatCategoryResponse.isRight()) { - ResponseFormat errorRespons = validatCategoryResponse.right().value(); - return Either.right(errorRespons); - } - if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { - if (!hasBeenCertified) { - currentService.setCategories(categoryUpdated); - } else { - log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); - ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); - return Either.right(errorResponse); - } - } - return Either.left(true); - - } - - public Either validateServiceCategory(List list) { - if (list != null) { - if (list.size() > 1) { - log.debug("Must be only one category for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - CategoryDefinition category = list.get(0); - if (category.getSubcategories() != null) { - log.debug("Subcategories cannot be defined for service"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY); - return Either.right(responseFormat); - } - if (!ValidationUtils.validateStringNotEmpty(category.getName())) { - log.debug("Resource category is empty"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - return Either.right(responseFormat); - } - - log.debug("validating service category {} against valid categories list", list); - Either, ActionStatus> categorys = elementDao.getAllServiceCategories(); - if (categorys.isRight()) { - log.debug("failed to retrive service categories from Titan"); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); - return Either.right(responseFormat); - } - List categoryList = categorys.left().value(); - for (CategoryDefinition value : categoryList) { - if (value.getName().equals(category.getName())) { - return Either.left(true); - } - } - log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); - } - return Either.left(false); - } - - public ResponseFormat deleteService(String serviceId, User user) { - ResponseFormat responseFormat; - String ecompErrorContext = "delete service"; - - Either eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - user = eitherCreator.left().value(); - - Either serviceStatus = toscaOperationFacade.getToscaElement(serviceId); - if (serviceStatus.isRight()) { - log.debug("failed to get service {}", serviceId); - return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), ""); - } - - Service service = serviceStatus.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - - result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) { - ResponseFormat responseFormat; - String ecompErrorContext = "delete service"; - Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return validateEmptyResult.right().value(); - } - - Either eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return eitherCreator.right().value(); - } - user = eitherCreator.left().value(); - - Either getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); - if (getResult.isRight()) { - return getResult.right().value(); - } - Service service = getResult.left().value(); - - StorageOperationStatus result = StorageOperationStatus.OK; - Either lockResult = lockComponent(service, "Mark service to delete"); - if (lockResult.isRight()) { - result = StorageOperationStatus.GENERAL_ERROR; - return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - } - - try { - result = markComponentToDelete(service); - if (result.equals(StorageOperationStatus.OK)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); - } else { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); - responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); - } - return responseFormat; - - } finally { - if (result == null || !result.equals(StorageOperationStatus.OK)) { - log.warn("operation failed. do rollback"); - BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } - } - - public Either getService(String serviceId, User user) { - String ecompErrorContext = "Get service"; - Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); - if (validateEmptyResult.isRight()) { - return Either.right(validateEmptyResult.right().value()); - } - - Either eitherCreator = validateUserExists(user, ecompErrorContext, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - log.debug("failed to get service by id {}", serviceId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId)); - } - - if(!(storageStatus.left().value() instanceof Service)){ - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId)); - } - Service service = storageStatus.left().value(); - return Either.left(service); - - - - - } - - public Either getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) { - Either resp = validateUserExists(userId, "get Service By Name And Version", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); - if (storageStatus.isRight()) { - log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName)); - } - Service service = storageStatus.left().value(); - return Either.left(service); - } - - @SuppressWarnings("unchecked") - private void createMandatoryArtifactsData(Service service, User user) { - // create mandatory artifacts - - // TODO it must be removed after that artifact uniqueId creation will be - // moved to ArtifactOperation - // String serviceUniqueId = - // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion()); - String serviceUniqueId = service.getUniqueId(); - Map artifactMap = service.getArtifacts(); - if (artifactMap == null) - artifactMap = new HashMap(); - - Map informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts(); - List exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); - - String category = service.getCategories().get(0).getName(); - boolean isCreateArtifact = true; - if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { - for (String exlude : exludeServiceCategory) { - if (exlude.equalsIgnoreCase(category)) { - isCreateArtifact = false; - break; - } - } - - } - - if (informationalServiceArtifacts != null && isCreateArtifact) { - Set keys = informationalServiceArtifacts.keySet(); - for (String informationalServiceArtifactName : keys) { - Map artifactInfoMap = (Map) informationalServiceArtifacts.get(informationalServiceArtifactName); - ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false); - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - - } - - service.setArtifacts(artifactMap); - } - } - - private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map artifactInfoMap, User user, Boolean isServiceApi) { - - ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); - - if (isServiceApi) { - artifactInfo.setMandatory(false); - artifactInfo.setServiceApi(true); - } - return artifactInfo; - } - - private Either validateTransitionEnum(String distributionTransition, User user) { - DistributionTransitionEnum transitionEnum = null; - - transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); - if (transitionEnum == null) { - BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution"); - log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); - ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(error); - } - - return Either.left(transitionEnum); - } - - private Either validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) { - String data = comment.getUserRemarks(); - - if (data == null || data.trim().isEmpty()) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); - log.debug("user comment cannot be empty or null."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - data = ValidationUtils.removeNoneUtf8Chars(data); - data = ValidationUtils.removeHtmlTags(data); - data = ValidationUtils.normaliseWhitespace(data); - data = ValidationUtils.stripOctets(data); - - if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); - log.debug("user comment exceeds limit."); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); - } - if (!ValidationUtils.validateIsEnglish(data)) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - return Either.left(data); - } - - private Either validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { - Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); - createAudit(user, auditAction, comment, responseFormat); - return Either.right(responseFormat); - } - Service service = storageStatus.left().value(); - - if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { - log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); - createAudit(user, auditAction, comment, service, responseFormat); - return Either.right(responseFormat); - } - return Either.left(service); - } - - private Either validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { - log.debug("get user from DB"); - - // get user details - Either eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - user = eitherCreator.left().value(); - - // validate user role - List roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.GOVERNOR); - roles.add(Role.OPS); - Either validateRes = validateUserRole(user, service, roles, auditAction, comment); - if (validateRes.isRight()) { - return Either.right(validateRes.right().value()); - } - return Either.left(user); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, ResponseFormat responseFormat) { - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - - createAudit(user, auditAction, comment, null, responseFormat, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) { - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, component.getDistributionStatus().name()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, component.getDistributionStatus().name()); - createAudit(user, auditAction, comment, component, component.getLifecycleState().name(), component.getVersion(), responseFormat, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat, EnumMap auditingFields) { - log.debug("audit before sending response"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - componentsUtils.auditComponent(responseFormat, user, component, null, null, auditAction, ComponentTypeEnum.SERVICE, auditingFields); - } - - private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, String prevState, String prevVersion, ResponseFormat responseFormat, EnumMap auditingFields) { - log.debug("audit before sending response"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment); - componentsUtils.auditComponent(responseFormat, user, component, prevState, prevVersion, auditAction, ComponentTypeEnum.SERVICE, auditingFields); - } - - public Either activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { - - Either eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false); - if (eitherCreator.isRight()) { - return Either.right(eitherCreator.right().value()); - } - - User user = eitherCreator.left().value(); - - Either result = null; - ResponseFormat response = null; - Service updatedService = null; - String did = ThreadLocalsHolder.getUuid(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did); - // DE194021 - String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); - if (configuredEnvName != null && false == envName.equals(configuredEnvName)) { - log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName); - envName = configuredEnvName; - } - // DE194021 - - ServletContext servletContext = request.getSession().getServletContext(); - boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE - if (!isDistributionEngineUp) { - BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN"); - log.debug("Distribution Engine is DOWN"); - response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(response); - } - - Either serviceRes = toscaOperationFacade.getToscaElement(serviceId); - if (serviceRes.isRight()) { - log.debug("failed retrieving service"); - response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); - componentsUtils.auditComponent(response, user, null, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields); - return Either.right(response); - } - Service service = serviceRes.left().value(); - String dcurrStatus = service.getDistributionStatus().name(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, dcurrStatus); - - Either readyForDistribution = distributionEngine.isReadyForDistribution(service, did, envName); - if (readyForDistribution.isLeft()) { - INotificationData notificationData = readyForDistribution.left().value(); - StorageOperationStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName()); - if (notifyServiceResponse == StorageOperationStatus.OK) { - Either updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED); - if (updateStateRes.isLeft() && updateStateRes.left().value() != null) { - updatedService = updateStateRes.left().value(); - dcurrStatus = updatedService.getDistributionStatus().name(); - } else { - // The response is not relevant - updatedService = service; - } - ASDCKpiApi.countActivatedDistribution(); - response = componentsUtils.getResponseFormat(ActionStatus.OK); - result = Either.left(updatedService); - } else { - BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); - log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); - response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - result = Either.right(response); - } - } else { - StorageOperationStatus distEngineValidationResponse = readyForDistribution.right().value(); - response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(distEngineValidationResponse), service.getName(), envName); - result = Either.right(response); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, dcurrStatus); - componentsUtils.auditComponent(response, user, service, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields); - return result; - } - - // convert to private after deletion of temp url - public Either updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { - - Either resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - String serviceId = service.getUniqueId(); - Either lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation"); - if (lockResult.isRight()) { - return Either.right(lockResult.right().value()); - } - try { - Either result = toscaOperationFacade.updateDistributionStatus(service, user, state); - if (result.isRight()) { - titanDao.rollback(); - BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); - log.debug("service {} change distribution status failed", serviceId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - titanDao.commit(); - return Either.left(result.left().value()); - } finally { - graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); - } - } - - public Either markDistributionAsDeployed(String serviceId, String did, User user) { - - Either resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - - log.debug("mark distribution deployed"); - - AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; - Either getServiceResponse = toscaOperationFacade.getToscaElement(serviceId); - if (getServiceResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId); - log.debug("service {} not found", serviceId); - ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); - - return Either.right(responseFormat); - } - - Service service = getServiceResponse.left().value(); - - Either validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service); - if (validateRoleForDeploy.isRight()) { - return Either.right(validateRoleForDeploy.right().value()); - } - user = validateRoleForDeploy.left().value(); - - return checkDistributionAndDeploy(did, user, auditAction, service); - - } - - public Either generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) { - Function>> artifactTaskGeneratorCreator = ri -> - // Only one VF Module Artifact per instance - add it to a list of one - buildArtifactGenList(service, modifier, shouldLock, ri); - - return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); - - } - - private List> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) { - List> asList = new ArrayList>(); - - if (ri.getOriginType() == OriginTypeEnum.VF) { - asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock)); - } - return asList; - } - - private List collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper responseWrapper) { - - return currVF.getGroupInstances(); - } - - private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List groupsForCurrVF, Wrapper payloadWrapper, Wrapper responseWrapper) { - ArtifactDefinition vfModuleAertifact = null; - if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { - Optional optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); - if (optionalVfModuleArtifact.isPresent()) { - vfModuleAertifact = optionalVfModuleArtifact.get(); - } - } - if (vfModuleAertifact == null) { - Either createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement()); - if (createVfModuleArtifact.isLeft()) { - vfModuleAertifact = createVfModuleArtifact.left().value(); - } else { - responseWrapper.setInnerElement(createVfModuleArtifact.right().value()); - } - } - return vfModuleAertifact; - } - - private void fillVfModuleInstHeatEnvPayload(List groupsForCurrVF, Wrapper payloadWrapper) { - // Converts GroupDefinition to VfModuleArtifactPayload which is the - // format used in the payload - - // List vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList()); - List vfModulePayloadForCurrVF = new ArrayList(); - if (groupsForCurrVF != null) { - for (GroupInstance groupInstance : groupsForCurrVF) { - VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance); - vfModulePayloadForCurrVF.add(modulePayload); - } - Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); - // Update Payload With Heat Env -// vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); - - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); - payloadWrapper.setInnerElement(vfModulePayloadString); - } - - } - - private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) { - ArtifactDefinition vfModuleAertifact = null; - Wrapper responseWrapper = new Wrapper<>(); - Wrapper payloadWrapper = new Wrapper<>(); - List groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); - if (responseWrapper.isEmpty()) { - fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper); - } - if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { - vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); - } - if (responseWrapper.isEmpty() && vfModuleAertifact != null) { - vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service); - } - - Either result; - if (responseWrapper.isEmpty()) { - result = Either.left(vfModuleAertifact); - } else { - result = Either.right(responseWrapper.getInnerElement()); - } - - return result; - } - - private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper, Service service) { - ArtifactDefinition result = null; -// final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); -// if (eitherResource.isRight()) { -// responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); -// } else if (!payloadWrapper.isEmpty()) { -// Resource resource = eitherResource.left().value(); - Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), - () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); - if (eitherPayload.isLeft()) { - result = eitherPayload.left().value(); - } else { - responseWrapper.setInnerElement(eitherPayload.right().value()); - } -// } - if (result == null) { - result = vfModuleArtifact; - } - - return result; - } - - private Either createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) { - - ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition(); - String newCheckSum = null; - - vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact"); - vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata"); - vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType()); - vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata"); - vfModuleArtifactDefinition.setTimeout(0); - vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json"); - vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString); - if (vfModulePayloadString != null) { - newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes()); - } - vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); - - Either addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); - - Either result; - if (addArifactToComponent.isLeft()) { - result = Either.left(addArifactToComponent.left().value()); - } else { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value()))); - } - - return result; - } - - public Either generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock) { - - Function>> artifactTaskGeneratorCreator = resourceInstance -> - // Get All Deployment Artifacts - service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()). - // Filter in Only Heat Env - filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())). - // Create ArtifactGenerator from those Artifacts - map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList()); - - return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator); - - } - - private Either generateDeploymentArtifacts(Service service, User modifier, Function>> artifactTaskGeneratorCreator) { - - // Get Flat List of (Callable) ArtifactGenerator for all the RI in the - // service - if (service.getComponentInstances() != null) { - List> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); - if (artifactGenList != null && !artifactGenList.isEmpty()) { - for (ArtifactGenerator entry : artifactGenList) { - Either callRes; - try { - callRes = entry.call(); - if (callRes.isRight()) { - log.debug("Failed to generate artifact error : {}", callRes.right().value()); - return Either.right(callRes.right().value()); - } - } catch (Exception e) { - log.debug("Failed to generate artifact exception : {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } - } - return Either.left(service); - } - - abstract class ArtifactGenerator implements Callable> { - - } - - class HeatEnvArtifactGenerator extends ArtifactGenerator { - ArtifactDefinition artifactDefinition; - Service service; - String resourceInstanceName; - User modifier; - String instanceId; - boolean shouldLock; - - HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) { - this.artifactDefinition = artifactDefinition; - this.service = service; - this.resourceInstanceName = resourceInstanceName; - this.modifier = modifier; - this.shouldLock = shouldLock; - this.instanceId = instanceId; - } - - @Override - public Either call() throws Exception { - return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId); - } - - public ArtifactDefinition getArtifactDefinition() { - return artifactDefinition; - } - - } - - class VfModuleArtifacGenerator extends ArtifactGenerator { - private User user; - private ComponentInstance componentInstance; - private Service service; - boolean shouldLock; - - @Override - public Either call() throws Exception { - return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock); - } - - private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) { - super(); - this.user = user; - this.componentInstance = componentInstance; - this.service = service; - this.shouldLock = shouldLock; - } - - } - - private synchronized Either checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { - boolean isDeployed = isDistributionDeployed(did, service); - if (isDeployed) { - return Either.left(service); - } - Either distributionSuccess = checkDistributionSuccess(did, user, auditAction, service); - if (distributionSuccess.isRight()) { - return Either.right(distributionSuccess.right().value()); - } - - log.debug("mark distribution {} as deployed - success", did); - componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user); - return Either.left(service); - } - - private boolean isDistributionDeployed(String did, Service service) { - Either, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); - - boolean isDeployed = false; - if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) { - // already deployed - log.debug("distribution {} is already deployed", did); - isDeployed = true; - } - return isDeployed; - } - - protected Either checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) { - - log.trace("checkDistributionSuccess"); - // get all "DRequest" records for this distribution - // Either, ActionStatus> distRequestsResponse = - // auditingDao.getListOfDistributionByAction(did, - // AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), "", - // ResourceAdminEvent.class); - Either, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); - if (distRequestsResponse.isRight()) { - ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value()); - return Either.right(error); - } - - List distributionRequests = distRequestsResponse.left().value(); - if (distributionRequests.isEmpty()) { - BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did); - log.info("distribution {} is not found", did); - ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND); - return Either.right(error); - } - boolean isRequestSucceeded = false; - for (ResourceAdminEvent event : distributionRequests) { - String eventStatus = event.getStatus(); - if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { - isRequestSucceeded = true; - break; - } - } - - // get all "DNotify" records for this distribution - // Either, ActionStatus> - // distNotificationsResponse = - // auditingDao.getListOfDistributionByAction(did, - // AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), "", - // DistributionNotificationEvent.class); - Either, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); - if (distNotificationsResponse.isRight()) { - ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value()); - return Either.right(error); - } - - List distributionNotifications = distNotificationsResponse.left().value(); - boolean isNotificationsSucceeded = false; - for (DistributionNotificationEvent event : distributionNotifications) { - String eventStatus = event.getStatus(); - if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { - isNotificationsSucceeded = true; - break; - } - } - - // if request failed OR there are notifications that failed - if (!(isRequestSucceeded && isNotificationsSucceeded)) { - - log.info("distribution {} has failed", did); - ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); - auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); - return Either.right(error); - } - return Either.left(true); - } - - private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) { - - ResponseFormat error = componentsUtils.getResponseFormat(status, params); - String message = ""; - if (error.getMessageId() != null) { - message = error.getMessageId() + ": "; - } - message += error.getFormattedMessage(); - - if (service != null) { - componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user); - } else { - componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user); - } - return error; - } - - private Either validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { - Either eitherCreator = userAdmin.getUser(user.getUserId(), false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); - log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); - auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); - return Either.right(responseFormat); - } - user = eitherCreator.left().value(); - log.debug("validate user role"); - List roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.OPS); - Either validateRes = validateUserRole(user, service, roles, auditAction, null); - if (validateRes.isRight()) { - log.info("role {} is not allowed to perform this action", user.getRole()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - return Either.left(user); - - } - - @Override - public void setDeploymentArtifactsPlaceHolder(Component component, User user) { - - } - - @Override - public Either, ResponseFormat> deleteMarkedComponents() { - return deleteMarkedComponents(ComponentTypeEnum.SERVICE); - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return serviceComponentInstanceBusinessLogic; - } - - @Override - public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - - Either resp = validateUserExists(userId, "Get Component Instances", false); - if (resp.isRight()) { - return Either.right(resp.right().value()); - } - Either getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - if (getComponentRes.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); - return Either.right(responseFormat); - } - - List componentInstances = getComponentRes.left().value().getComponentInstances(); - // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList()); - - return Either.left(componentInstances); - } - - public ICacheMangerOperation getCacheManagerOperation() { - return cacheManagerOperation; - } - - public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { - this.cacheManagerOperation = cacheManagerOperation; - } - - /** - * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date - * - * @param modifier - * @param serviceId - * @param componentInstanceId - * @param groupInstanceId - * @param newProperties - * @return - */ - public Either, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List newProperties) { - - Either, ResponseFormat> actionResult = null; - Either, ResponseFormat> validateUserAndComponentRes; - Component component = null; - Either lockResult = null; - log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId); - try { - validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier); - if (validateUserAndComponentRes.isRight()) { - log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId); - actionResult = Either.right(validateUserAndComponentRes.right().value()); - } - if (actionResult == null) { - component = validateUserAndComponentRes.left().value().getKey(); - lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service"); - if (lockResult.isRight()) { - log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage()); - actionResult = Either.right(lockResult.right().value()); - } else { - log.debug("The service with system name {} locked. ", component.getSystemName()); - } - } - if (actionResult == null) { - actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); - if (actionResult.isRight()) { - log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage()); - } - } - } catch (Exception e) { - log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service); - } - } - return actionResult; - } - - private Either, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List newProperties) { - - Either, ResponseFormat> actionResult = null; - Either, ResponseFormat> findGroupInstanceRes; - Either, ResponseFormat> updateParentsModificationTimeRes; - ComponentInstance relatedComponentInstance = null; - GroupInstance oldGroupInstance = null; - Either updateGroupInstanceResult = null; - GroupInstance updatedGroupInstance = null; - boolean inTransaction = true; - boolean shouldCloseTransaction = true; - findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId); - if (findGroupInstanceRes.isRight()) { - log.debug("Group instance {} not found. ", groupInstanceId); - actionResult = Either.right(findGroupInstanceRes.right().value()); - } - if (actionResult == null) { - oldGroupInstance = findGroupInstanceRes.left().value().getValue(); - relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); - updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction); - if (updateGroupInstanceResult.isRight()) { - log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(updateGroupInstanceResult.right().value()); - } - } - if (actionResult == null) { - updatedGroupInstance = updateGroupInstanceResult.left().value(); - if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) { - updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction); - if (updateParentsModificationTimeRes.isRight()) { - log.debug("Failed to update modification time. ", oldGroupInstance.getName()); - actionResult = Either.right(updateParentsModificationTimeRes.right().value()); - } - } - } - if (actionResult == null) { - actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties()); - } - return actionResult; - } - - private Either, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, - boolean inTranscation, boolean shouldCloseTransaction) { - - Either, ResponseFormat> actionResult; - Either serviceMetadataUpdateResult; - Either updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, - updatedGroupInstance.getModificationTime(), inTranscation); - if (updateComponentInstanceRes.isRight()) { - log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName()); - actionResult = Either.right(updateComponentInstanceRes.right().value()); - } else { - serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime()); - if (serviceMetadataUpdateResult.isRight()) { - log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value()))); - } else { - actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value())); - } - } - return actionResult; - } - - private Either, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { - - Either, ResponseFormat> result = null; - Either validateComponentExistsRes = null; - User currUser = null; - Component component = null; - Either validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); - if (validationUserResult.isRight()) { - log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId); - result = Either.right(validationUserResult.right().value()); - } - if (result == null) { - currUser = validationUserResult.left().value(); - validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); - if (validateComponentExistsRes.isRight()) { - log.debug("Failed to validate service existing {}. ", serviceId); - result = Either.right(validateComponentExistsRes.right().value()); - } - } - if (result == null) { - component = validateComponentExistsRes.left().value(); - if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { - log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>(component, currUser)); - } - return result; - } - - private Either, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { - - Either, ResponseFormat> actionResult = null; - GroupInstance groupInstance = null; - ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId); - if (foundComponentInstance == null) { - log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName())); - } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) { - groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); - if (groupInstance == null) { - log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName())); - } - } - if (actionResult == null) { - actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance)); - } - return actionResult; - } - - private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { - ComponentInstance componentInstance = null; - if (!CollectionUtils.isEmpty(component.getComponentInstances())) { - componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); - } - return componentInstance; - } - - private Either validateUserIgnoreAudit(User modifier, String ecompErrorContext) { - Either result = validateUser(modifier, ecompErrorContext, null, null, false); - if (result.isLeft()) { - List roles = new ArrayList<>(); - roles.add(Role.ADMIN); - roles.add(Role.DESIGNER); - Either validationRoleRes = validateUserRole(result.left().value(), roles); - if (validationRoleRes.isRight()) { - result = Either.right(validationRoleRes.right().value()); - } - } - return result; - } - - public Either getUiComponentDataTransferByComponentId(String serviceId, List dataParamsToReturn) { - - ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); - - if (serviceResultEither.isRight()) { - if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { - log.debug("Failed to found service with id {} ", serviceId); - Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); - } - - log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); - return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); - } - - Service service = serviceResultEither.left().value(); - UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); - return Either.left(dataTransfer); - } + private static final String STATUS_SUCCESS_200 = "200"; + + private static final String STATUS_DEPLOYED = "DEPLOYED"; + + @Autowired + private IElementOperation elementDao; + + @Autowired + private IDistributionEngine distributionEngine; + + @Autowired + private AuditCassandraDao auditCassandraDao; + + @Autowired + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @Autowired + private GroupBusinessLogic groupBusinessLogic; + + @Autowired + private ICacheMangerOperation cacheManagerOperation; + + @Autowired + private ServiceDistributionValidation serviceDistributionValidation; + + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class); + private static final String INITIAL_VERSION = "0.1"; + @Autowired + private ForwardingPathOperation forwardingPathOperation; + + @Autowired + private ForwardingPathValidator forwardingPathValidator; + + public ServiceBusinessLogic() { + log.debug("ServiceBusinessLogic started"); + } + + public Either changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) { + + Either resp = validateUserExists(user.getUserId(), "change Service Distribution State", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("check request state"); + Either validateEnum = validateTransitionEnum(state, user); + if (validateEnum.isRight()) { + return Either.right(validateEnum.right().value()); + } + DistributionTransitionEnum distributionTransition = validateEnum.left().value(); + AuditingActionEnum auditAction = distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT; + Either commentResponse = validateComment(commentObj, user, auditAction); + if (commentResponse.isRight()) { + return Either.right(commentResponse.right().value()); + } + String comment = commentResponse.left().value(); + + Either validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment); + if (validateService.isRight()) { + return Either.right(validateService.right().value()); + } + Service service = validateService.left().value(); + Either validateUser = validateUserDistributionChange(user, service, auditAction, comment); + if (validateUser.isRight()) { + return Either.right(validateUser.right().value()); + } + user = validateUser.left().value(); + + // lock resource + + Either lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(responseFormat); + } + + try { + + DistributionStatusEnum newState; + if (distributionTransition == DistributionTransitionEnum.APPROVE) { + newState = DistributionStatusEnum.DISTRIBUTION_APPROVED; + } else { + newState = DistributionStatusEnum.DISTRIBUTION_REJECTED; + } + Either result = toscaOperationFacade.updateDistributionStatus(service, user, newState); + if (result.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState"); + log.debug("service {} is change destribuation status failed", service.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName()); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + Service updatedService = result.left().value(); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, ComponentTypeEnum.SERVICE, ResourceAuditData.newBuilder().build(), comment); + return Either.left(result.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + + } + + public Either>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) { + Either resp = validateUserExists(userId, "get Component Audit Records", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either>, ActionStatus> result; + try { + + // Certified Version + if (componentVersion.endsWith(".0")) { + Either, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID); + if (eitherAuditingForCertified.isLeft()) { + result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value())); + } else { + result = Either.right(eitherAuditingForCertified.right().value()); + } + } + // Uncertified Version + else { + result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion); + } + } catch (Exception e) { + log.debug("get Audit Records failed with exception {}", e); + result = Either.right(ActionStatus.GENERAL_ERROR); + } + + if (result.isRight()) { + return Either.right(componentsUtils.getResponseFormat(result.right().value())); + } else { + return Either.left(result.left().value()); + } + + } + + private Either>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) { + // First Query + Either, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion); + + if (eitherprevVerAudit.isRight()) { + return Either.right(eitherprevVerAudit.right().value()); + } + + // Second Query + Either, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion); + if (eitherCurrVerAudit.isRight()) { + return Either.right(eitherCurrVerAudit.right().value()); + } + + List> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value()); + List> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value()); + + List> duplicateElements = new ArrayList>(); + duplicateElements.addAll(prevVerAuditList); + duplicateElements.retainAll(currVerAuditList); + + List> joinedNonDuplicatedList = new ArrayList>(); + joinedNonDuplicatedList.addAll(prevVerAuditList); + joinedNonDuplicatedList.removeAll(duplicateElements); + joinedNonDuplicatedList.addAll(currVerAuditList); + + return Either.left(joinedNonDuplicatedList); + } + + private List> getAuditingFieldsList(List prevVerAuditList) { + + List> prevVerAudit = new ArrayList>(); + for (AuditingGenericEvent auditEvent : prevVerAuditList) { + auditEvent.fillFields(); + prevVerAudit.add(auditEvent.getFields()); + } + return prevVerAudit; + } + + /** + * createService + * + * @param service + * - Service + * @param user + * - modifier data (userId) + * @return Either + */ + public Either createService(Service service, User user) { + + // get user details + Either eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, service, new ArrayList(), AuditingActionEnum.CREATE_RESOURCE, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + service.setCreatorUserId(user.getUserId()); + + // warn on overridden fields + checkFieldsForOverideAttampt(service); + // enrich object + log.debug("enrich service with version and state"); + service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setVersion(INITIAL_VERSION); + service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); + service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + + Either createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE); + if (createServiceResponse.isRight()) { + return createServiceResponse; + } + return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user); + } + + private void checkFieldsForOverideAttampt(Service service) { + checkComponentFieldsForOverrideAttempt(service); + if (service.getDistributionStatus() != null) { + log.info("Distribution Status cannot be defined by user. This field will be overridden by the application"); + } + } + + private Either createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) { + log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + Either lockResult = lockComponentByName(service.getSystemName(), service, "Create Service"); + if (lockResult.isRight()) { + ResponseFormat responseFormat = lockResult.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult); + + try { + + createMandatoryArtifactsData(service, user); + createServiceApiArtifactsData(service, user); + setToscaArtifactsPlaceHolders(service, user); + Either genericServiceEither = fetchAndSetDerivedFromGenericType(service); + if (genericServiceEither.isRight()) + return Either.right(genericServiceEither.right().value()); + + generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value()); + + Either dataModelResponse = toscaOperationFacade.createToscaComponent(service); + + // service created successfully!!! + if (dataModelResponse.isLeft()) { + log.debug("Service created successfully!!!"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + ASDCKpiApi.countCreatedServicesKPI(); + return Either.left(dataModelResponse.left().value()); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE); + log.debug("audit before sending response"); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + + } finally { + graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service); + } + } + + @SuppressWarnings("unchecked") + private void createServiceApiArtifactsData(Service service, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + String serviceUniqueId = service.getUniqueId(); + Map artifactMap = service.getServiceApiArtifacts(); + if (artifactMap == null) + artifactMap = new HashMap(); + + Map serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts(); + List exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); + + List categories = service.getCategories(); + boolean isCreateArtifact = true; + if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { + for (String exlude : exludeServiceCategory) { + if (exlude.equalsIgnoreCase(categories.get(0).getName())) { + isCreateArtifact = false; + break; + } + } + + } + + if (serviceApiArtifacts != null && isCreateArtifact) { + Set keys = serviceApiArtifacts.keySet(); + for (String serviceApiArtifactName : keys) { + Map artifactInfoMap = (Map) serviceApiArtifacts.get(serviceApiArtifactName); + ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + } + + service.setServiceApiArtifacts(artifactMap); + } + } + + private Either validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) { + + Either validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum); + if (validationResponse.isRight()) { + return Either.right(validationResponse.right().value()); + } + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + service.setContactId(service.getContactId().toLowerCase()); + + // Generate invariant UUID - must be here and not in operation since it + // should stay constant during clone + String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); + service.setInvariantUUID(invariantUUID); + + return Either.left(service); + } + + private Either validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { + Either componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum); + if (componentsFieldsValidation.isRight()) { + return componentsFieldsValidation; + } + + log.debug("validate service name uniqueness"); + Either serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum); + if (serviceNameUniquenessValidation.isRight()) { + return serviceNameUniquenessValidation; + } + + log.debug("validate category"); + Either categoryValidation = validateServiceCategory(user, service, actionEnum); + if (categoryValidation.isRight()) { + return categoryValidation; + } + + // validate project name (ProjectCode) - mandatory in service + log.debug("validate projectName"); + Either projectCodeValidation = validateProjectCode(user, service, actionEnum); + if (projectCodeValidation.isRight()) { + return projectCodeValidation; + } + + log.debug("validate service type"); + Either serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum); + if (serviceTypeValidation.isRight()) { + return serviceTypeValidation; + } + + log.debug("validate service role"); + Either serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum); + if (serviceRoleValidation.isRight()) { + return serviceRoleValidation; + } + + return Either.left(true); + + } + + private Either validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) { + log.debug("validate Service category"); + + if (service.getCategories() == null || service.getCategories().size() == 0) { + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + + Either validatCategory = validateServiceCategory(service.getCategories()); + if (validatCategory.isRight()) { + ResponseFormat responseFormat = validatCategory.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + return Either.left(true); + } + + public Either, ResponseFormat> validateServiceNameExists(String serviceName, String userId) { + + Either resp = validateUserExists(userId, "validate Service Name Exists", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + Either dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE); + + // DE242223 + titanDao.commit(); + + if (dataModelResponse.isLeft()) { + Map result = new HashMap<>(); + result.put("isValid", dataModelResponse.left().value()); + log.debug("validation was successfully performed."); + return Either.left(result); + } + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value())); + + return Either.right(responseFormat); + } + + public void setElementDao(IElementOperation elementDao) { + this.elementDao = elementDao; + } + + public void setCassandraAuditingDao(AuditCassandraDao auditingDao) { + this.auditCassandraDao = auditingDao; + } + + public ArtifactsBusinessLogic getArtifactBl() { + return artifactsBusinessLogic; + } + + public void setArtifactBl(ArtifactsBusinessLogic artifactBl) { + this.artifactsBusinessLogic = artifactBl; + } + + public Either updateServiceMetadata(String serviceId, Service serviceUpdate, User user) { + Either eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + + Service currentService = storageStatus.left().value(); + + if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + + Either validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate); + if (validationRsponse.isRight()) { + log.info("service update metadata: validations field."); + return validationRsponse; + } + Service serviceToUpdate = validationRsponse.left().value(); + // lock resource + + Either lockResult = lockComponent(serviceId, currentService, "Update Service Metadata"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate); + if (updateResponse.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata"); + log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + return Either.left(updateResponse.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public Either, ResponseFormat> deleteForwardingPaths(String serviceId, Set pathIdsToDelete, User user, boolean lock) { + Service serviceToDelete = initServiceToDeletePaths(serviceId, pathIdsToDelete); + Either eitherCreator = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + Service service = storageStatus.left().value(); + Either, StorageOperationStatus> result = null; + if (lock) { + Either lockResult = lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service"); + if (lockResult.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + } + try{ + result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete); + if (result.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", service.getName(), result.right().value()); + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); + } + titanDao.commit(); + log.debug("The service with system name {} locked. ", service.getSystemName()); + + } catch (Exception e){ + log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); + } + return Either.left(result.left().value()); + } + + private Service initServiceToDeletePaths(String serviceId, Collection pathIdsToDelete) { + Service serviceToDelete = new Service(); + serviceToDelete.setUniqueId(serviceId); + serviceToDelete.setForwardingPaths(new HashMap<>()); + pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition())); + return serviceToDelete; + } + + public Either updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock); + } + + public Either createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) { + return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock); + } + + private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path){ + ForwardingPathDataDefinition dataDefinition = new ForwardingPathDataDefinition(path.getName()); + dataDefinition.setName(Strings.nullToEmpty(path.getName()).trim()); + dataDefinition.setProtocol(Strings.nullToEmpty(path.getProtocol()).trim()); + dataDefinition.setDestinationPortNumber(Strings.nullToEmpty(path.getDestinationPortNumber()).trim()); + dataDefinition.setUniqueId(path.getUniqueId()); + dataDefinition.setPathElements(path.getPathElements()); + dataDefinition.setDescription(path.getDescription()); + dataDefinition.setToscaResourceName(path.getToscaResourceName()); + return dataDefinition; + } + + private Either createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) { + Either eitherCreator1 = validateUserAndRole(serviceUpdate, user, errorContext); + if (eitherCreator1 != null) return eitherCreator1; + + Map forwardingPaths = serviceUpdate.getForwardingPaths(); + + Map trimmedForwardingPaths = + forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue())))); + + Either booleanResponseFormatEither = forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), + serviceId, isUpdate); + if(booleanResponseFormatEither.isRight()){ + return Either.right(booleanResponseFormatEither.right().value()); + } + + Either serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); + + if(serviceStorageOperationStatusEither.isRight()){ + StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); + log.debug("Failed to fetch service information by service id, error {}", errorStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + } + Service storedService = serviceStorageOperationStatusEither.left().value(); + + Set forwardingPathDataDefinitions = trimmedForwardingPaths.entrySet().stream().map(entry -> entry.getValue()) + .collect(Collectors.toSet()); + + Either result; + Either forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME); + if (forwardingPathOrigin.isRight()) { + StorageOperationStatus errorStatus = forwardingPathOrigin.right().value(); + log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + } + Component component = forwardingPathOrigin.left().value(); + final String toscaResourceName; + if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) { + toscaResourceName = ((Resource) component).getToscaResourceName(); + } else { + toscaResourceName = ""; + } + Either lockResult = null; + if (lock) { + lockResult = + lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service"); + if (lockResult.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(), + lockResult.right().value().getFormattedMessage()); + return Either.right(lockResult.right().value()); + } else { + log.debug("The service with system name {} locked. ", storedService.getSystemName()); + } + } + Map resultMap = new HashMap<>(); + try { + trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName)); + + try { + for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) { + if (isUpdate) { + result = forwardingPathOperation.updateForwardingPath(serviceId, forwardingPathDataDefinition); + } else { + result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition); + } + if (result.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), + "")); + } else { + ForwardingPathDataDefinition fpDataDefinition = result.left().value(); + resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition); + } + } + + } catch (Exception e) { + titanDao.rollback(); + log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), + e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + } finally { + if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); + } + } + Service service = createServiceWithForwardingPathForResponse(serviceId, resultMap); + return Either.left(service); + } + + private Service createServiceWithForwardingPathForResponse(String serviceId, Map forwardingPathDataDefinitionMap) { + Service service = new Service(); + service.setUniqueId(serviceId); + service.setForwardingPaths(forwardingPathDataDefinitionMap); + return service; + } + + private Either validateUserAndRole(Service serviceUpdate, User user, String errorContext) { + Either eitherCreator = validateUser(user, errorContext, serviceUpdate, null, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + Either validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + return null; + }private Either validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) { + + boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion()); + Either response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String creatorUserIdUpdated = serviceUpdate.getCreatorUserId(); + String creatorUserIdCurrent = currentService.getCreatorUserId(); + if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) { + log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated); + } + + String creatorFullNameUpdated = serviceUpdate.getCreatorFullName(); + String creatorFullNameCurrent = currentService.getCreatorFullName(); + if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) { + log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated); + } + + String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId(); + String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId(); + if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) { + log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated); + } + + String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName(); + String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName(); + if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) { + log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated); + } + + response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus(); + DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus(); + if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals(distributionStatusCurrent != null ? distributionStatusCurrent.name() : null)) { + log.info("update service: received request to update distributionStatus to {}. the field is read only, ignoring.", distributionStatusUpdated); + } + + if (serviceUpdate.getProjectCode() != null) { + response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + } + + response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + Long creationDateUpdated = serviceUpdate.getCreationDate(); + Long creationDateCurrent = currentService.getCreationDate(); + if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) { + log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated); + } + + String versionUpdated = serviceUpdate.getVersion(); + String versionCurrent = currentService.getVersion(); + if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) { + log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated); + } + + response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateContactId(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate(); + Long lastUpdateDateCurrent = currentService.getLastUpdateDate(); + if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) { + log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated); + } + + LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState(); + LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState(); + if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) { + log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated); + } + + Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion(); + Boolean isHighestVersionCurrent = currentService.isHighestVersion(); + if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) { + log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated); + } + + String uuidUpdated = serviceUpdate.getUUID(); + String uuidCurrent = currentService.getUUID(); + if (!uuidCurrent.equals(uuidUpdated)) { + log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated); + } + + response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null); + if (response.isRight()) { + ResponseFormat errorResponse = response.right().value(); + return Either.right(errorResponse); + } + + String currentInvariantUuid = currentService.getInvariantUUID(); + String updatedInvariantUuid = serviceUpdate.getInvariantUUID(); + + if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) { + log.warn("Product invariant UUID is automatically set and cannot be updated"); + serviceUpdate.setInvariantUUID(currentInvariantUuid); + } + validateAndUpdateEcompNaming(currentService, serviceUpdate); + + currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext()); + + return Either.left(currentService); + + } + + private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) { + Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming(); + Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming(); + if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr.equals(isEcompoGeneratedUpdate)) { + currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate); + } + String namingPolicyUpd = serviceUpdate.getNamingPolicy(); + if (!currentService.isEcompGeneratedNaming()) { + if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) { + log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false"); + currentService.setNamingPolicy(""); + } else { + currentService.setNamingPolicy(namingPolicyUpd); + } + }else{ + currentService.setNamingPolicy(namingPolicyUpd); + } + } + + private Either validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + String contactIdUpdated = serviceUpdate.getContactId(); + String contactIdCurrent = currentService.getContactId(); + if (!contactIdCurrent.equals(contactIdUpdated)) { + Either validatContactId = validateContactId(user, serviceUpdate, audatingAction); + if (validatContactId.isRight()) { + ResponseFormat errorRespons = validatContactId.right().value(); + return Either.right(errorRespons); + } + currentService.setContactId(contactIdUpdated.toLowerCase()); + } + return Either.left(true); + } + + private Either validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + List tagsUpdated = serviceUpdate.getTags(); + List tagsCurrent = currentService.getTags(); + if (tagsUpdated == null || tagsUpdated.isEmpty()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS); + componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + + if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) { + Either validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction); + if (validatResponse.isRight()) { + ResponseFormat errorRespons = validatResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setTags(tagsUpdated); + } + return Either.left(true); + } + + private Either validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + String descriptionUpdated = serviceUpdate.getDescription(); + String descriptionCurrent = currentService.getDescription(); + if (!descriptionCurrent.equals(descriptionUpdated)) { + Either validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction); + if (validateDescriptionResponse.isRight()) { + ResponseFormat errorRespons = validateDescriptionResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setDescription(serviceUpdate.getDescription()); + } + return Either.left(true); + } + + private Either validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) { + String projectCodeUpdated = serviceUpdate.getProjectCode(); + String projectCodeCurrent = currentService.getProjectCode(); + if (!projectCodeCurrent.equals(projectCodeUpdated)) { + + Either validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction); + if (validatProjectCodeResponse.isRight()) { + ResponseFormat errorRespons = validatProjectCodeResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setProjectCode(projectCodeUpdated); + + } + return Either.left(true); + } + + private Either validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + String iconUpdated = serviceUpdate.getIcon(); + String iconCurrent = currentService.getIcon(); + if (!iconCurrent.equals(iconUpdated)) { + if (!hasBeenCertified) { + Either validatIconResponse = validateIcon(user, serviceUpdate, audatingAction); + if (validatIconResponse.isRight()) { + ResponseFormat errorRespons = validatIconResponse.right().value(); + return Either.right(errorRespons); + } + currentService.setIcon(iconUpdated); + } else { + log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) { + String serviceNameUpdated = serviceUpdate.getName(); + String serviceNameCurrent = currentService.getName(); + if (!serviceNameCurrent.equals(serviceNameUpdated)) { + if (!hasBeenCertified) { + Either validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction); + if (validatServiceNameResponse.isRight()) { + ResponseFormat errorRespons = validatServiceNameResponse.right().value(); + return Either.right(errorRespons); + } + + Either serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction); + if (serviceNameUniquenessValidation.isRight()) { + return serviceNameUniquenessValidation; + } + currentService.setName(serviceNameUpdated); + currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated)); + currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated)); + + } else { + log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + } + + private Either validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { + String updatedServiceType = updatedService.getServiceType(); + String currentServiceType = currentService.getServiceType(); + if (!currentServiceType.equals(updatedServiceType)) { + Either validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction); + if (validateServiceType.isRight()) { + ResponseFormat errorResponse = validateServiceType.right().value(); + componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + currentService.setServiceType(updatedServiceType); + } + return Either.left(true); + } + + protected Either validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + String serviceType = ((Service)component).getServiceType(); + if (serviceType != null){ + serviceType = cleanUpText(serviceType); + Either validateServiceType = validateServiceType(serviceType); + if (validateServiceType.isRight()) { + ResponseFormat responseFormat = validateServiceType.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + return Either.left(true); + } else { + return Either.left(false); + } + } + + + private Either validateServiceType(String serviceType) { + if (serviceType.equals("")){ + return Either.left(true); + } else { + if (!ValidationUtils.validateServiceTypeLength(serviceType)) { + log.info("service type exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateIsEnglish(serviceType)) { + log.info("service type is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + private Either validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) { + String updatedServiceRole = updatedService.getServiceRole(); + String currentServiceRole = currentService.getServiceRole(); + if (!currentServiceRole.equals(updatedServiceRole)) { + Either validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction); + if (validateServiceRole.isRight()) { + ResponseFormat errorResponse = validateServiceRole.right().value(); + componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE); + return Either.right(errorResponse); + } + currentService.setServiceRole(updatedServiceRole); + } + return Either.left(true); + } + + protected Either validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) { + String serviceRole = ((Service)component).getServiceRole(); + if (serviceRole != null){ + serviceRole = cleanUpText(serviceRole); + + Either validateServiceRole = validateServiceRole(serviceRole); + if (validateServiceRole.isRight()) { + ResponseFormat responseFormat = validateServiceRole.right().value(); + componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE); + return Either.right(responseFormat); + } + return Either.left(true); + } else { + return Either.left(false); + } + } + + + private Either validateServiceRole(String serviceRole) { + if (serviceRole.equals("")){ + return Either.left(true); + } else { + if (!ValidationUtils.validateServiceRoleLength(serviceRole)) { + log.info("service role exceeds limit."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH); + return Either.right(errorResponse); + } + + if (!ValidationUtils.validateIsEnglish(serviceRole)) { + log.info("service role is not valid."); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE); + return Either.right(errorResponse); + } + return Either.left(true); + } + } + + + + private Either validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) { + List categoryUpdated = serviceUpdate.getCategories(); + List categoryCurrent = currentService.getCategories(); + Either validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction); + if (validatCategoryResponse.isRight()) { + ResponseFormat errorRespons = validatCategoryResponse.right().value(); + return Either.right(errorRespons); + } + if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) { + if (!hasBeenCertified) { + currentService.setCategories(categoryUpdated); + } else { + log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated); + ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED); + return Either.right(errorResponse); + } + } + return Either.left(true); + + } + + public Either validateServiceCategory(List list) { + if (list != null) { + if (list.size() > 1) { + log.debug("Must be only one category for service"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue()); + return Either.right(responseFormat); + } + CategoryDefinition category = list.get(0); + if (category.getSubcategories() != null) { + log.debug("Subcategories cannot be defined for service"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY); + return Either.right(responseFormat); + } + if (!ValidationUtils.validateStringNotEmpty(category.getName())) { + log.debug("Resource category is empty"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + return Either.right(responseFormat); + } + + log.debug("validating service category {} against valid categories list", list); + Either, ActionStatus> categorys = elementDao.getAllServiceCategories(); + if (categorys.isRight()) { + log.debug("failed to retrive service categories from Titan"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value()); + return Either.right(responseFormat); + } + List categoryList = categorys.left().value(); + for (CategoryDefinition value : categoryList) { + if (value.getName().equals(category.getName())) { + return Either.left(true); + } + } + log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue())); + } + return Either.left(false); + } + + public Either getServiceComponentsRelations(String serviceId, User user) { + Either serviceResponseFormatEither = getService(serviceId, user); + if (serviceResponseFormatEither.isRight()){ + return Either.right(serviceResponseFormatEither.right().value()); + } + final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value()); + return Either.left(serviceRelations); + + + }public ResponseFormat deleteService(String serviceId, User user) { + ResponseFormat responseFormat; + String ecompErrorContext = "delete service"; + + Either eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + user = eitherCreator.left().value(); + + Either serviceStatus = toscaOperationFacade.getToscaElement(serviceId); + if (serviceStatus.isRight()) { + log.debug("failed to get service {}", serviceId); + return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), ""); + } + + Service service = serviceStatus.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either lockResult = lockComponent(service, "Mark service to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + + result = markComponentToDelete(service); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) { + ResponseFormat responseFormat; + String ecompErrorContext = "delete service"; + Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return validateEmptyResult.right().value(); + } + + Either eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return eitherCreator.right().value(); + } + user = eitherCreator.left().value(); + + Either getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId()); + if (getResult.isRight()) { + return getResult.right().value(); + } + Service service = getResult.left().value(); + + StorageOperationStatus result = StorageOperationStatus.OK; + Either lockResult = lockComponent(service, "Mark service to delete"); + if (lockResult.isRight()) { + result = StorageOperationStatus.GENERAL_ERROR; + return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } + + try { + result = markComponentToDelete(service); + if (result.equals(StorageOperationStatus.OK)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT); + } else { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result); + responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName()); + } + return responseFormat; + + } finally { + if (result == null || !result.equals(StorageOperationStatus.OK)) { + log.warn("operation failed. do rollback"); + BeEcompErrorManager.getInstance().logBeSystemError("Delete Service"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); + } + } + + public Either getService(String serviceId, User user) { + String ecompErrorContext = "Get service"; + Either validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext); + if (validateEmptyResult.isRight()) { + return Either.right(validateEmptyResult.right().value()); + } + + Either eitherCreator = validateUserExists(user, ecompErrorContext, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + log.debug("failed to get service by id {}", serviceId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId)); + } + + if(!(storageStatus.left().value() instanceof Service)){ + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId)); + } + Service service = storageStatus.left().value(); + return Either.left(service); + + + + + } + + public Either getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) { + Either resp = validateUserExists(userId, "get Service By Name And Version", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion); + if (storageStatus.isRight()) { + log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName)); + } + Service service = storageStatus.left().value(); + return Either.left(service); + } + + @SuppressWarnings("unchecked") + private void createMandatoryArtifactsData(Service service, User user) { + // create mandatory artifacts + + // TODO it must be removed after that artifact uniqueId creation will be + // moved to ArtifactOperation + String serviceUniqueId = service.getUniqueId(); + Map artifactMap = service.getArtifacts(); + if (artifactMap == null) + artifactMap = new HashMap(); + + Map informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts(); + List exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory(); + + String category = service.getCategories().get(0).getName(); + boolean isCreateArtifact = true; + if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) { + for (String exlude : exludeServiceCategory) { + if (exlude.equalsIgnoreCase(category)) { + isCreateArtifact = false; + break; + } + } + + } + + if (informationalServiceArtifacts != null && isCreateArtifact) { + Set keys = informationalServiceArtifacts.keySet(); + for (String informationalServiceArtifactName : keys) { + Map artifactInfoMap = (Map) informationalServiceArtifacts.get(informationalServiceArtifactName); + ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false); + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + + } + + service.setArtifacts(artifactMap); + } + } + + private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map artifactInfoMap, User user, Boolean isServiceApi) { + + ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL); + + if (isServiceApi) { + artifactInfo.setMandatory(false); + artifactInfo.setServiceApi(true); + } + return artifactInfo; + } + + private Either validateTransitionEnum(String distributionTransition, User user) { + DistributionTransitionEnum transitionEnum = null; + + transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition); + if (transitionEnum == null) { + BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution"); + log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString()); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(error); + } + + return Either.left(transitionEnum); + } + + private Either validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) { + String data = comment.getUserRemarks(); + + if (data == null || data.trim().isEmpty()) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); + log.debug("user comment cannot be empty or null."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + data = ValidationUtils.removeNoneUtf8Chars(data); + data = ValidationUtils.removeHtmlTags(data); + data = ValidationUtils.normaliseWhitespace(data); + data = ValidationUtils.stripOctets(data); + + if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution"); + log.debug("user comment exceeds limit."); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); + } + if (!ValidationUtils.validateIsEnglish(data)) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + return Either.left(data); + } + + private Either validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) { + Either storageStatus = toscaOperationFacade.getToscaElement(serviceId); + if (storageStatus.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId); + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, auditAction, serviceId, ComponentTypeEnum.SERVICE, comment); + return Either.right(responseFormat); + } + Service service = storageStatus.left().value(); + + if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) { + log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName()); + createAudit(user, auditAction, comment, service, responseFormat); + return Either.right(responseFormat); + } + return Either.left(service); + } + + private Either validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) { + log.debug("get user from DB"); + + // get user details + Either eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + user = eitherCreator.left().value(); + + // validate user role + List roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.GOVERNOR); + roles.add(Role.OPS); + Either validateRes = validateUserRole(user, service, roles, auditAction, comment); + if (validateRes.isRight()) { + return Either.right(validateRes.right().value()); + } + return Either.left(user); + } + + private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) { + log.debug("audit before sending response"); + componentsUtils.auditComponent(responseFormat, user, component, auditAction, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(component.getVersion()).build(), comment); + } + + private String getEnvNameFromConfiguration() { + String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + log.trace("Update environment name to be {}", configuredEnvName); + return configuredEnvName; + } + + public Either activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) { + + Either activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data); + if (activationRequestInformationEither.isRight()) { + return Either.right(activationRequestInformationEither.right().value()); + } + + ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value(); + + Either result = null; + ResponseFormat response = null; + String did = ThreadLocalsHolder.getUuid(); + Service service = activationRequestInformation.getServiceToActivate(); + + StorageOperationStatus readyForDistribution = distributionEngine.verifyServiceHasDeploymentArtifacts(service); + if (readyForDistribution.equals(StorageOperationStatus.OK)) { + result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier); + } else { + response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envId); + result = Either.right(response); + } + return result; + } + + public Either buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) { + String envName = getEnvNameFromConfiguration(); + INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext); + ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier.getUserId(), modifier.getFullName()); + if (notifyServiceResponse == ActionStatus.OK) { + return Either.left(did); + } else { + BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); + log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESPONSE_FROM_PROXY); + return Either.right(error); + } + } + + public Either activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) { + + Either eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false); + if (eitherCreator.isRight()) { + return Either.right(eitherCreator.right().value()); + } + + User user = eitherCreator.left().value(); + + Either result = null; + ResponseFormat response = null; + Service updatedService = null; + String did = ThreadLocalsHolder.getUuid(); + // DE194021 + String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0); + if (configuredEnvName != null && false == envName.equals(configuredEnvName)) { + log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName); + envName = configuredEnvName; + } + // DE194021 + + ServletContext servletContext = request.getSession().getServletContext(); + boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE + if (!isDistributionEngineUp) { + BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN"); + log.debug("Distribution Engine is DOWN"); + response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(response); + } + + Either serviceRes = toscaOperationFacade.getToscaElement(serviceId); + if (serviceRes.isRight()) { + log.debug("failed retrieving service"); + response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId); + componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().build(), did); + return Either.right(response); + } + Service service = serviceRes.left().value(); + String dcurrStatus = service.getDistributionStatus().name(); + String updatedStatus = dcurrStatus; + StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(service, envName); + if (readyForDistribution.equals(StorageOperationStatus.OK)) { + INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null); + ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName()); + if (notifyServiceResponse == ActionStatus.OK) { + Either updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED); + if (updateStateRes.isLeft() && updateStateRes.left().value() != null) { + updatedService = updateStateRes.left().value(); + updatedStatus = updatedService.getDistributionStatus().name(); + } else { + // The response is not relevant + updatedService = service; + } + ASDCKpiApi.countActivatedDistribution(); + response = componentsUtils.getResponseFormat(ActionStatus.OK); + result = Either.left(updatedService); + } else { + BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification"); + log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse); + response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + result = Either.right(response); + } + } else { + response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envName); + result = Either.right(response); + } + componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().distributionStatus(dcurrStatus).build(), + ResourceAuditData.newBuilder().distributionStatus(updatedStatus).build(), service.getName(), + null, null, did); + return result; + } + + // convert to private after deletion of temp url + public Either updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) { + + Either resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + String serviceId = service.getUniqueId(); + Either lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation"); + if (lockResult.isRight()) { + return Either.right(lockResult.right().value()); + } + try { + Either result = toscaOperationFacade.updateDistributionStatus(service, user, state); + if (result.isRight()) { + titanDao.rollback(); + BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation"); + log.debug("service {} change distribution status failed", serviceId); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + titanDao.commit(); + return Either.left(result.left().value()); + } finally { + graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service); + } + } + + public Either markDistributionAsDeployed(String serviceId, String did, User user) { + + Either resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + + log.debug("mark distribution deployed"); + + AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY; + Either getServiceResponse = toscaOperationFacade.getToscaElement(serviceId); + if (getServiceResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId); + log.debug("service {} not found", serviceId); + ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), ""); + + return Either.right(responseFormat); + } + + Service service = getServiceResponse.left().value(); + + Either validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service); + if (validateRoleForDeploy.isRight()) { + return Either.right(validateRoleForDeploy.right().value()); + } + user = validateRoleForDeploy.left().value(); + + return checkDistributionAndDeploy(did, user, auditAction, service); + + } + + public Either generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) { + Function>> artifactTaskGeneratorCreator = ri -> + // Only one VF Module Artifact per instance - add it to a list of one + buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri); + + return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator); + + } + + private List> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) { + List> asList = new ArrayList>(); + + if (ri.getOriginType() == OriginTypeEnum.VF) { + asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock, inTransaction)); + } + return asList; + } + + private List collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper responseWrapper) { + Map deploymentArtifacts = currVF.getDeploymentArtifacts(); + if(currVF.getGroupInstances() != null){ + currVF.getGroupInstances().stream().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts)); + } + return currVF.getGroupInstances(); + } + + private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List groupsForCurrVF, Wrapper payloadWrapper, Wrapper responseWrapper) { + ArtifactDefinition vfModuleAertifact = null; + if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) { + Optional optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny(); + if (optionalVfModuleArtifact.isPresent()) { + vfModuleAertifact = optionalVfModuleArtifact.get(); + } + } + if (vfModuleAertifact == null) { + Either createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement()); + if (createVfModuleArtifact.isLeft()) { + vfModuleAertifact = createVfModuleArtifact.left().value(); + } else { + responseWrapper.setInnerElement(createVfModuleArtifact.right().value()); + } + } + return vfModuleAertifact; + } + + private void fillVfModuleInstHeatEnvPayload(List groupsForCurrVF, Wrapper payloadWrapper) { + // Converts GroupDefinition to VfModuleArtifactPayload which is the + // format used in the payload + + List vfModulePayloadForCurrVF = new ArrayList(); + if (groupsForCurrVF != null) { + for (GroupInstance groupInstance : groupsForCurrVF) { + VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance); + vfModulePayloadForCurrVF.add(modulePayload); + } + Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); + + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF); + payloadWrapper.setInnerElement(vfModulePayloadString); + } + + } + + private Either generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) { + ArtifactDefinition vfModuleAertifact = null; + Wrapper responseWrapper = new Wrapper<>(); + Wrapper payloadWrapper = new Wrapper<>(); + List groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper); + if (responseWrapper.isEmpty()) { + fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper); + } + if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) { + vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); + } + if (responseWrapper.isEmpty() && vfModuleAertifact != null) { + vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service); + } + + Either result; + if (responseWrapper.isEmpty()) { + result = Either.left(vfModuleAertifact); + } else { + result = Either.right(responseWrapper.getInnerElement()); + } + + return result; + } + + private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper payloadWrapper, Wrapper responseWrapper, Service service) { + ArtifactDefinition result = null; + Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, () -> System.currentTimeMillis(), + () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); + if (eitherPayload.isLeft()) { + result = eitherPayload.left().value(); + } else { + responseWrapper.setInnerElement(eitherPayload.right().value()); + } + if (result == null) { + result = vfModuleArtifact; + } + + return result; + } + + private Either createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) { + + ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition(); + String newCheckSum = null; + + vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact"); + vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata"); + vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType()); + vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata"); + vfModuleArtifactDefinition.setTimeout(0); + vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json"); + vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString); + if (vfModulePayloadString != null) { + newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes()); + } + vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum); + + Either addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId()); + + Either result; + if (addArifactToComponent.isLeft()) { + result = Either.left(addArifactToComponent.left().value()); + } else { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value()))); + } + + return result; + } + + public Either generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) { + + Function>> artifactTaskGeneratorCreator = resourceInstance -> + // Get All Deployment Artifacts + service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()). + // Filter in Only Heat Env + filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())). + // Create ArtifactGenerator from those Artifacts + map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction, resourceInstance.getUniqueId())).collect(Collectors.toList()); + + return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator); + + } + + private Either generateDeploymentArtifacts(Service service, Function>> artifactTaskGeneratorCreator) { + + // Get Flat List of (Callable) ArtifactGenerator for all the RI in the + // service + if (service.getComponentInstances() != null) { + List> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList()); + if (artifactGenList != null && !artifactGenList.isEmpty()) { + for (ArtifactGenerator entry : artifactGenList) { + Either callRes; + try { + callRes = entry.call(); + if (callRes.isRight()) { + log.debug("Failed to generate artifact error : {}", callRes.right().value()); + return Either.right(callRes.right().value()); + } + } catch (Exception e) { + log.debug("Failed to generate artifact exception : {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } + } + Either storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); + if (storageStatus.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); + } + + Service currentService = storageStatus.left().value(); + + return Either.left(currentService); + + } + + abstract class ArtifactGenerator implements Callable> { + + } + + class HeatEnvArtifactGenerator extends ArtifactGenerator { + ArtifactDefinition artifactDefinition; + Service service; + String resourceInstanceName; + User modifier; + String instanceId; + boolean shouldLock; + boolean inTransaction; + + HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) { + this.artifactDefinition = artifactDefinition; + this.service = service; + this.resourceInstanceName = resourceInstanceName; + this.modifier = modifier; + this.shouldLock = shouldLock; + this.instanceId = instanceId; + this.inTransaction = inTransaction; + } + + @Override + public Either call() throws Exception { + return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId); + } + + public ArtifactDefinition getArtifactDefinition() { + return artifactDefinition; + } + + } + + class VfModuleArtifacGenerator extends ArtifactGenerator { + private User user; + private ComponentInstance componentInstance; + private Service service; + boolean shouldLock; + boolean inTransaction; + + @Override + public Either call() throws Exception { + return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction); + } + + private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock, boolean inTransaction) { + super(); + this.user = user; + this.componentInstance = componentInstance; + this.service = service; + this.shouldLock = shouldLock; + this.inTransaction = inTransaction; + } + + } + + private synchronized Either checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { + boolean isDeployed = isDistributionDeployed(did, service); + if (isDeployed) { + return Either.left(service); + } + Either distributionSuccess = checkDistributionSuccess(did, user, auditAction, service); + if (distributionSuccess.isRight()) { + return Either.right(distributionSuccess.right().value()); + } + + log.debug("mark distribution {} as deployed - success", did); + componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user); + return Either.left(service); + } + + private boolean isDistributionDeployed(String did, Service service) { + Either, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED); + + boolean isDeployed = false; + if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) { + // already deployed + log.debug("distribution {} is already deployed", did); + isDeployed = true; + } + return isDeployed; + } + + protected Either checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) { + + log.trace("checkDistributionSuccess"); + // get all "DRequest" records for this distribution + + Either, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + if (distRequestsResponse.isRight()) { + ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value()); + return Either.right(error); + } + + List distributionRequests = distRequestsResponse.left().value(); + if (distributionRequests.isEmpty()) { + BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did); + log.info("distribution {} is not found", did); + ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND); + return Either.right(error); + } + boolean isRequestSucceeded = false; + for (ResourceAdminEvent event : distributionRequests) { + String eventStatus = event.getStatus(); + if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { + isRequestSucceeded = true; + break; + } + } + + // get all "DNotify" records for this distribution + Either, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + if (distNotificationsResponse.isRight()) { + ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value()); + return Either.right(error); + } + + List distributionNotifications = distNotificationsResponse.left().value(); + boolean isNotificationsSucceeded = false; + for (DistributionNotificationEvent event : distributionNotifications) { + String eventStatus = event.getStatus(); + if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) { + isNotificationsSucceeded = true; + break; + } + } + + // if request failed OR there are notifications that failed + if (!(isRequestSucceeded && isNotificationsSucceeded)) { + + log.info("distribution {} has failed", did); + ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); + auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did); + return Either.right(error); + } + return Either.left(true); + } + + private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) { + + ResponseFormat error = componentsUtils.getResponseFormat(status, params); + String message = ""; + if (error.getMessageId() != null) { + message = error.getMessageId() + ": "; + } + message += error.getFormattedMessage(); + + if (service != null) { + componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user); + } else { + componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user); + } + return error; + } + + private Either validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) { + Either eitherCreator = userAdmin.getUser(user.getUserId(), false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId()); + log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId()); + auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND); + return Either.right(responseFormat); + } + user = eitherCreator.left().value(); + log.debug("validate user role"); + List roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.OPS); + Either validateRes = validateUserRole(user, service, roles, auditAction, null); + if (validateRes.isRight()) { + log.info("role {} is not allowed to perform this action", user.getRole()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + return Either.left(user); + + } + + @Override + public void setDeploymentArtifactsPlaceHolder(Component component, User user) { + + } + + @Override + public Either, ResponseFormat> deleteMarkedComponents() { + return deleteMarkedComponents(ComponentTypeEnum.SERVICE); + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return componentInstanceBusinessLogic; + } + + @Override + public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + + Either resp = validateUserExists(userId, "Get Component Instances", false); + if (resp.isRight()) { + return Either.right(resp.right().value()); + } + Either getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + if (getComponentRes.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value())); + return Either.right(responseFormat); + } + + List componentInstances = getComponentRes.left().value().getComponentInstances(); + + return Either.left(componentInstances); + } + + public ICacheMangerOperation getCacheManagerOperation() { + return cacheManagerOperation; + } + + public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) { + this.cacheManagerOperation = cacheManagerOperation; + } + + public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation) { + this.forwardingPathOperation = forwardingPathOperation; + } + + @Override + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + }/** + * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date + * + * @param modifier + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param newProperties + * @return + */ + public Either, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List newProperties) { + + Either, ResponseFormat> actionResult = null; + Either, ResponseFormat> validateUserAndComponentRes; + Component component = null; + Either lockResult = null; + log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId); + try { + validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier); + if (validateUserAndComponentRes.isRight()) { + log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId); + actionResult = Either.right(validateUserAndComponentRes.right().value()); + } + if (actionResult == null) { + component = validateUserAndComponentRes.left().value().getKey(); + lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service"); + if (lockResult.isRight()) { + log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage()); + actionResult = Either.right(lockResult.right().value()); + } else { + log.debug("The service with system name {} locked. ", component.getSystemName()); + } + } + if (actionResult == null) { + actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties); + if (actionResult.isRight()) { + log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage()); + } + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { + graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service); + } + } + return actionResult; + } + + private Either, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List newProperties) { + + Either, ResponseFormat> actionResult = null; + Either, ResponseFormat> findGroupInstanceRes; + Either, ResponseFormat> updateParentsModificationTimeRes; + ComponentInstance relatedComponentInstance = null; + GroupInstance oldGroupInstance = null; + Either updateGroupInstanceResult = null; + GroupInstance updatedGroupInstance = null; + boolean inTransaction = true; + boolean shouldCloseTransaction = true; + findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId); + if (findGroupInstanceRes.isRight()) { + log.debug("Group instance {} not found. ", groupInstanceId); + actionResult = Either.right(findGroupInstanceRes.right().value()); + } + if (actionResult == null) { + oldGroupInstance = findGroupInstanceRes.left().value().getValue(); + relatedComponentInstance = findGroupInstanceRes.left().value().getKey(); + updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction); + if (updateGroupInstanceResult.isRight()) { + log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); + actionResult = Either.right(updateGroupInstanceResult.right().value()); + } + } + if (actionResult == null) { + updatedGroupInstance = updateGroupInstanceResult.left().value(); + if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) { + updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction); + if (updateParentsModificationTimeRes.isRight()) { + log.debug("Failed to update modification time. ", oldGroupInstance.getName()); + actionResult = Either.right(updateParentsModificationTimeRes.right().value()); + } + } + } + if (actionResult == null) { + actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties()); + } + return actionResult; + } + + private Either, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, + boolean inTranscation, boolean shouldCloseTransaction) { + + Either, ResponseFormat> actionResult; + Either serviceMetadataUpdateResult; + Either updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance, + updatedGroupInstance.getModificationTime(), inTranscation); + if (updateComponentInstanceRes.isRight()) { + log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(updateComponentInstanceRes.right().value()); + } else { + serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime()); + if (serviceMetadataUpdateResult.isRight()) { + log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value()))); + } else { + actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value())); + } + } + return actionResult; + } + + private Either, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) { + + Either, ResponseFormat> result = null; + Either validateComponentExistsRes = null; + User currUser = null; + Component component = null; + Either validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues"); + if (validationUserResult.isRight()) { + log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId); + result = Either.right(validationUserResult.right().value()); + } + if (result == null) { + currUser = validationUserResult.left().value(); + validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null); + if (validateComponentExistsRes.isRight()) { + log.debug("Failed to validate service existing {}. ", serviceId); + result = Either.right(validateComponentExistsRes.right().value()); + } + } + if (result == null) { + component = validateComponentExistsRes.left().value(); + if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) { + log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>(component, currUser)); + } + return result; + } + + private Either, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) { + + Either, ResponseFormat> actionResult = null; + GroupInstance groupInstance = null; + ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId); + if (foundComponentInstance == null) { + log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName())); + } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) { + groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null); + if (groupInstance == null) { + log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName()); + actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName())); + } + } + if (actionResult == null) { + actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance)); + } + return actionResult; + } + + private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) { + ComponentInstance componentInstance = null; + if (!CollectionUtils.isEmpty(component.getComponentInstances())) { + componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null); + } + return componentInstance; + } + + private Either validateUserIgnoreAudit(User modifier, String ecompErrorContext) { + Either result = validateUser(modifier, ecompErrorContext, null, null, false); + if (result.isLeft()) { + List roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.DESIGNER); + Either validationRoleRes = validateUserRole(result.left().value(), roles); + if (validationRoleRes.isRight()) { + result = Either.right(validationRoleRes.right().value()); + } + } + return result; + } + + public Either getUiComponentDataTransferByComponentId(String serviceId, List dataParamsToReturn) { + + ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); + Either serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); + + if (serviceResultEither.isRight()) { + if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found service with id {} ", serviceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); + } + + log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); + return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); + } + + Service service = serviceResultEither.left().value(); + UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn); + return Either.left(dataTransfer); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java deleted file mode 100644 index d1cc93acc8..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.springframework.stereotype.Component; - -@Component("serviceComponentInstanceBusinessLogic") -public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - return NodeTypeEnum.Resource; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java deleted file mode 100644 index c5db7ee022..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components.impl; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component("vfComponentInstanceBusinessLogic") -public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic { - - private static Logger log = LoggerFactory.getLogger(VFComponentInstanceBusinessLogic.class.getName()); - - @Override - protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() { - return NodeTypeEnum.Resource; - } - - @Override - protected ComponentTypeEnum getComponentTypeOfComponentInstance() { - return ComponentTypeEnum.RESOURCE_INSTANCE; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java new file mode 100644 index 0000000000..6347bc2eaf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java @@ -0,0 +1,44 @@ +package org.openecomp.sdc.be.components.impl.exceptions; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +public class ComponentException extends RuntimeException { + + /** + * This class will be initialized either by action status and params or by ResponseFormat + */ + + private final transient ResponseFormat responseFormat; + + private final ActionStatus actionStatus; + private final String[] params; + + public ComponentException(ResponseFormat responseFormat) { + this(responseFormat, ActionStatus.OK, null); + } + + public ComponentException(ActionStatus actionStatus, String... params) { + this(null, actionStatus, params); + } + + private ComponentException(ResponseFormat responseFormat, ActionStatus actionStatus, String... params) { + this.actionStatus = actionStatus; + this.params = params; + this.responseFormat = responseFormat; + } + + public ResponseFormat getResponseFormat() { + return responseFormat; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } + + public String[] getParams() { + return params; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java index 7f6abe7f2c..236be437af 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java @@ -1,9 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -20,7 +17,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; @org.springframework.stereotype.Component public class GenericTypeBusinessLogic { @@ -81,6 +80,9 @@ public class GenericTypeBusinessLogic { } private String getGenericTypeToscaName(T component) { + if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){ + return component.getDerivedFromGenericType(); + } return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java new file mode 100644 index 0000000000..30a93fa0bc --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class PolicyTypeImportUtils { + + private PolicyTypeImportUtils() { + } + + public static boolean isPolicyTypesEquals(PolicyTypeDefinition pt1, PolicyTypeDefinition pt2) { + if (pt1 == pt2) { + return true; + } + if (pt1 == null || pt2 == null) { + return false; + } + return Objects.equals(pt1.getType(), pt2.getType()) && + Objects.equals(pt1.getVersion(), pt2.getVersion()) && + Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) && + Objects.equals(pt1.getTargets(), pt2.getTargets()) && + Objects.equals(pt1.getMetadata(), pt2.getMetadata()) && + Objects.equals(pt1.getDescription(), pt2.getDescription()) && + PolicyTypeImportUtils.isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties()); + } + + private static boolean isPolicyPropertiesEquals(List pt1Props, List pt2Props) { + if (pt1Props == pt2Props) { + return true; + } + if (pt1Props == null || pt2Props == null) { + return false; + } + if (isPropertiesListSizesNotEquals(pt1Props, pt2Props)) { + return false; + } + Map pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName); + long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count(); + return numberOfEqualsProperties == pt1Props.size(); + } + + private static boolean policyPropertyEquals(PropertyDefinition pt1Prop, PropertyDefinition pt2Prop) { + if (pt1Prop == pt2Prop) { + return true; + } + if (pt1Prop == null || pt2Prop == null) { + return false; + } + return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) && + Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition()) && + Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) && + Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword()) && + Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) && + Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType()) && + Objects.equals(pt1Prop.getType(), pt2Prop.getType()); + } + + private static boolean isPropertiesListSizesNotEquals(List pt1Props, List pt2Props) { + return CollectionUtils.isEmpty(pt1Props) && CollectionUtils.isNotEmpty(pt2Props) || + CollectionUtils.isEmpty(pt2Props) && CollectionUtils.isNotEmpty(pt1Props) || + pt1Props.size() != pt2Props.size(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java new file mode 100644 index 0000000000..df98a7f707 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java @@ -0,0 +1,66 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; +@org.springframework.stereotype.Component +public class GroupMembersUpdateOperation implements PostChangeVersionOperation { + + private static final Logger log = LoggerFactory.getLogger(GroupMembersUpdateOperation.class); + private final GroupsOperation groupsOperation; + private final ComponentsUtils componentsUtils; + + public GroupMembersUpdateOperation(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) { + this.groupsOperation = groupsOperation; + this.componentsUtils = componentsUtils; + } + + @Override + public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + return updateGroupMembersOnChangeVersion(container, prevVersion, newVersion); + } + + private ActionStatus updateGroupMembersOnChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#updateGroupMembersOnChangeVersion - replacing all group members for component instance {} with new component instance.", prevVersion.getUniqueId(), newVersion.getUniqueId()); + if (isEmpty(container.getGroups())) { + log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups.", container.getUniqueId()); + return ActionStatus.OK; + } + List groupsWithPrevInstAsMember = container.resolveGroupsByMember(prevVersion.getUniqueId()); + if (isEmpty(groupsWithPrevInstAsMember)) { + log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups with component instance {} as member.", container.getUniqueId(), prevVersion.getUniqueId()); + return ActionStatus.OK; + } + replacePrevInstanceMemberWithNewInstance(prevVersion, newVersion, groupsWithPrevInstAsMember); + return updateGroups(container, groupsWithPrevInstAsMember); + } + + private ActionStatus updateGroups(Component container, List groupsToUpdate) { + log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId()); + return groupsOperation.updateGroups(container, groupsToUpdate) + .either(groupsUpdated -> ActionStatus.OK, + err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType())); + } + + private void replacePrevInstanceMemberWithNewInstance(ComponentInstance prevVersion, ComponentInstance newVersion, List groupsWithPrevInstAsMember) { + groupsWithPrevInstAsMember.forEach(grp -> replacePrevInstanceMemberWithNewInstance(grp, prevVersion.getUniqueId(), newVersion.getUniqueId())); + } + + private void replacePrevInstanceMemberWithNewInstance(GroupDefinition groupDefinition, String prevInstanceId, String newInstanceId) { + Map membersNameToId = groupDefinition.getMembers(); + String prevInstanceMemberName = MapUtils.invertMap(membersNameToId).get(prevInstanceId).toString(); + membersNameToId.replace(prevInstanceMemberName, newInstanceId); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java new file mode 100644 index 0000000000..8824b2e097 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.function.UnaryOperator; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; + +@org.springframework.stereotype.Component +public class PolicyTargetsUpdateOperation implements PostChangeVersionOperation { + + private static final Logger log = LoggerFactory.getLogger(PolicyTargetsUpdateOperation.class); + private final ToscaOperationFacade toscaOperationFacade; + private final ComponentsUtils componentsUtils; + + public PolicyTargetsUpdateOperation(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) { + this.toscaOperationFacade = toscaOperationFacade; + this.componentsUtils = componentsUtils; + } + + @Override + public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + return replacePolicyTargetsInstanceId(container, prevVersion, newVersion); + } + + private ActionStatus replacePolicyTargetsInstanceId(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#replacePolicyTargetsInstanceId - replacing all policy targets for component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId()); + List policiesWithPrevInstanceAsTarget = container.resolvePoliciesByComponentInstanceTarget(prevVersion.getUniqueId()); + if (isEmpty(policiesWithPrevInstanceAsTarget)) { + return ActionStatus.OK; + } + replaceTargetsPrevInstanceIdWithNewInstanceId(prevVersion, newVersion, policiesWithPrevInstanceAsTarget); + return updatePolicies(container, policiesWithPrevInstanceAsTarget); + } + + private ActionStatus updatePolicies(Component policiesContainer, List policiesToUpdate) { + log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId()); + StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate); + return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType()); + } + + private void replaceTargetsPrevInstanceIdWithNewInstanceId(ComponentInstance prevVersion, ComponentInstance newVersion, List policiesWithPrevInstanceAsTarget) { + policiesWithPrevInstanceAsTarget.forEach(policy -> updatePolicyTargetWithNewInstanceVersion(policy, prevVersion.getUniqueId(), newVersion.getUniqueId())); + } + + private void updatePolicyTargetWithNewInstanceVersion(PolicyDefinition policyDefinition, String prevInstanceId, String newInstanceId) { + List policyInstanceTargets = policyDefinition.resolveComponentInstanceTargets(); + if (isEmpty(policyInstanceTargets)) { + return; + } + policyInstanceTargets.replaceAll(prevInstanceIdByNewInstanceId(prevInstanceId, newInstanceId)); + } + + private UnaryOperator prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) { + return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java new file mode 100644 index 0000000000..ee16c203bf --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +@FunctionalInterface +public interface PostChangeVersionOperation { + + ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java new file mode 100644 index 0000000000..ee37536886 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java @@ -0,0 +1,32 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Iterator; +import java.util.List; + +@org.springframework.stereotype.Component +public class PostChangeVersionOperationOrchestrator { + + private static final Logger log = LoggerFactory.getLogger(PostChangeVersionOperationOrchestrator.class); + private final List postChangeVersionOperations; + + public PostChangeVersionOperationOrchestrator(List postChangeVersionOperations) { + this.postChangeVersionOperations = postChangeVersionOperations; + } + + public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) { + log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId()); + ActionStatus postOperationsResult = ActionStatus.OK; + Iterator postChangeVersionIter = postChangeVersionOperations.iterator(); + while(postChangeVersionIter.hasNext() && postOperationsResult == ActionStatus.OK) { + postOperationsResult = postChangeVersionIter.next().onChangeVersion(container, prevVersion, newVersion); + } + return postOperationsResult; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java index 47e494f66d..c229d87593 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -45,151 +45,151 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class CertificationChangeTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class.getName()); - - private LifecycleStateEnum nextState; - private LifeCycleTransitionEnum name; - private AuditingActionEnum auditingAction; - private ArtifactsBusinessLogic artifactsManager; - - public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - this.name = name; - - // authorized roles - Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); - // TODO to be later defined for product - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.DESIGNER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - - switch (this.name) { - case CERTIFY: - this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; - this.nextState = LifecycleStateEnum.CERTIFIED; - break; - case FAIL_CERTIFICATION: - this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE; - nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; - break; - case CANCEL_CERTIFICATION: - this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE; - nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - break; - default: - break; - } - - } - - @Override - public LifeCycleTransitionEnum getName() { - return name; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return auditingAction; - } - - public ArtifactsBusinessLogic getArtifactsManager() { - return artifactsManager; - } - - public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { - this.artifactsManager = artifactsManager; - } - - private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph"); - log.debug("certification change failed on graph"); - - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - return responseFormat; - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - log.error("userRoleValidation failed"); - return userValidationResponse; - } - - if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION); - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE); - log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner); - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.info("start performing certification change for resource {}", component.getUniqueId()); - Either result = null; - - try { - Either certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); - if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - } else { - certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState); - } - - if (certificationChangeResult.isRight()) { - ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType); - result = Either.right(responseFormat); - return result; - } - - if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { - Either deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), - component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID()); - if (deleteOldComponentVersions.isRight()) { - ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType); - result = Either.right(responseFormat); - } - } - - result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value())); - return result; - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - - } + private static final Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class); + + private LifecycleStateEnum nextState; + private LifeCycleTransitionEnum name; + private AuditingActionEnum auditingAction; + private ArtifactsBusinessLogic artifactsManager; + + public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + this.name = name; + + // authorized roles + Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles)); + // TODO to be later defined for product + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + + switch (this.name) { + case CERTIFY: + this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE; + this.nextState = LifecycleStateEnum.CERTIFIED; + break; + case FAIL_CERTIFICATION: + this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE; + nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; + break; + case CANCEL_CERTIFICATION: + this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE; + nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; + break; + default: + break; + } + + } + + @Override + public LifeCycleTransitionEnum getName() { + return name; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return auditingAction; + } + + public ArtifactsBusinessLogic getArtifactsManager() { + return artifactsManager; + } + + public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) { + this.artifactsManager = artifactsManager; + } + + private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph"); + log.debug("certification change failed on graph"); + + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + return responseFormat; + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + log.error("userRoleValidation failed"); + return userValidationResponse; + } + + if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION); + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE); + log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner); + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.info("start performing certification change for resource {}", component.getUniqueId()); + Either result = null; + + try { + Either certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR); + if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { + certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + } else { + certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState); + } + + if (certificationChangeResult.isRight()) { + ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType); + result = Either.right(responseFormat); + return result; + } + + if (nextState.equals(LifecycleStateEnum.CERTIFIED)) { + Either deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), + component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID()); + if (deleteOldComponentVersions.isRight()) { + ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType); + result = Either.right(responseFormat); + } + } + + result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value())); + return result; + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java index 4a7f446739..dfd7beeaf1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; - +import fj.data.Either; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; @@ -35,21 +28,11 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; -import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; @@ -63,289 +46,257 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.*; public class CertificationRequestTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName()); - - private CapabilityOperation capabilityOperation; - private ServiceBusinessLogic serviceBusinessLogic; - public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, - CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - // Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER, - // Role.PRODUCT_STRATEGIST}; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - // TODO to be later defined for product - // addAuthorizedRoles(ComponentTypeEnum.PRODUCT, - // Arrays.asList(productCheckoutRoles)); - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.TESTER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - - this.serviceBusinessLogic = serviceBusinessLogic; - this.capabilityOperation = capabilityOperation; - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CERTIFICATION_REQUEST; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE; - } - - protected Either validateAllResourceInstanceCertified(Component component) { - Either eitherResult = Either.left(true); - - List resourceInstance = component.getComponentInstances(); - if (resourceInstance != null) { - Optional nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny(); - // Uncertified Resource Found - if (nonCertifiedRIOptional.isPresent()) { - ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get(); - ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType()); - eitherResult = Either.right(resFormat); - } - } - return eitherResult; - } - - private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) { - - ResponseFormat responseFormat; - Either eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); - if (eitherResource.isRight()) { - - responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - - } else { - ActionStatus actionStatus; - Resource resource = eitherResource.left().value(); - Either status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource); - - if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) { - if (status.isRight() || status.left().value() == null) { - actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND; - } else { - actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; - } - } else { - if (status.isRight() || status.left().value() == null) - actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES; - else { - actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; - } - - } - String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service"; - responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName()); - } - return responseFormat; - } - - private Either> validateMandatoryArtifactsSupplied(Map artifacts) { - - if (artifacts == null || artifacts.isEmpty()) { - return Either.left(ActionStatus.OK); - } - - Map invalidArtifacts = new HashMap<>(); - for (Entry artifact : artifacts.entrySet()) { - - ArtifactDefinition artifactDefinition = artifact.getValue(); - if (artifactDefinition.getMandatory()) { - String artifactEsId = artifactDefinition.getEsId(); - if (artifactEsId == null || artifactEsId.isEmpty()) { - invalidArtifacts.put(artifact.getKey(), artifactDefinition); - } - } - } - - if (invalidArtifacts.isEmpty()) { - return Either.left(ActionStatus.OK); - } else { - return Either.right(invalidArtifacts); - } - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing certification request for resource {}", component.getUniqueId()); - - ActionStatus actionStatus; - ResponseFormat responseFormat; - Either result = null; - try{ - if (component.getToscaType().equals(ToscaElementTypeEnum.TopologyTemplate.getValue())) { - - Either statusCert = validateAllResourceInstanceCertified(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); - } - - statusCert = validateConfiguredAtomicReqCapSatisfied(component); - if (statusCert.isRight()) { - return Either.right(statusCert.right().value()); - } - } - if (componentType == ComponentTypeEnum.SERVICE) { - - Either generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock); - - if (generateHeatEnvResult.isRight()) { - return Either.right(generateHeatEnvResult.right().value()); - } - Either generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock); - if (generateVfModuleResult.isRight()) { - return Either.right(generateVfModuleResult.right().value()); - } - } - - Either, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); - if (eitherPopulated != null && eitherPopulated.isRight()) { - return Either.right(eitherPopulated.right().value()); - } - - NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource; - - - Either certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - if (certificationRequestResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = certificationRequestResult.right().value(); - actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (!inTransaction) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (!inTransaction) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - private Either validateConfiguredAtomicReqCapSatisfied(Component component) { - log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId()); - List componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - // Prepare relationships data structures - // Better make it list than set in case we need to count req/cap - // occurrences in the future - Map> reqName2Ids = new HashMap<>(); - Map> capName2Ids = new HashMap<>(); -// Either parseRelationsForReqCapVerificationRes = parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids); -// if(parseRelationsForReqCapVerificationRes.isRight()){ -// return parseRelationsForReqCapVerificationRes; -// } - Map> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert(); - Map> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert(); - for (ComponentInstance compInst : componentInstances) { - String compInstId = compInst.getUniqueId(); - OriginTypeEnum originType = compInst.getOriginType(); - if (originType == null) { - log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId()); - continue; - } - String compInstType = originType.getValue(); - // Validating configured requirements fulfilled - if (null != requirementsToFulfillBeforeCert) { - Set reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType); - if (reqToFulfillForType != null) { - for (String reqNameToFulfill : reqToFulfillForType) { - List reqNameList = reqName2Ids.get(reqNameToFulfill); - if (reqNameList == null || !reqNameList.contains(compInstId)) { - log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType); - ComponentTypeEnum componentType = component.getComponentType(); - String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement", - reqNameToFulfill, "fulfilled"); - return Either.right(responseFormat); - } - } - } - } - // Validating configured capabilities consumed - if (null != capabilitiesToConsumeBeforeCert) { - Set capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType); - if (capToConsumeForType != null) { - for (String capNameToConsume : capToConsumeForType) { - List capNameList = capName2Ids.get(capNameToConsume); - if (capNameList == null || !capNameList.contains(compInstId)) { - log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType); - ComponentTypeEnum componentType = component.getComponentType(); - String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability", - capNameToConsume, "consumed"); - return Either.right(responseFormat); - } - } - } - } - } - } - log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId()); - return Either.left(true); - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // case of "atomic" checkin and certification request - modifier must be - // the owner - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - // other states - if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class); + + private CapabilityOperation capabilityOperation; + private ServiceBusinessLogic serviceBusinessLogic; + public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic, + CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + // TODO to be later defined for product + // addAuthorizedRoles(ComponentTypeEnum.PRODUCT, + // Arrays.asList(productCheckoutRoles)); + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.TESTER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + + this.serviceBusinessLogic = serviceBusinessLogic; + this.capabilityOperation = capabilityOperation; + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CERTIFICATION_REQUEST; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE; + } + + protected Either validateAllResourceInstanceCertified(Component component) { + Either eitherResult = Either.left(true); + + List resourceInstance = component.getComponentInstances(); + if (resourceInstance != null) { + Optional nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny(); + // Uncertified Resource Found + if (nonCertifiedRIOptional.isPresent()) { + ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get(); + ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType()); + eitherResult = Either.right(resFormat); + } + } + return eitherResult; + } + + private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) { + + ResponseFormat responseFormat; + Either eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid()); + if (eitherResource.isRight()) { + + responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + + } else { + ActionStatus actionStatus; + Resource resource = eitherResource.left().value(); + Either status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource); + + if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) { + if (status.isRight() || status.left().value() == null) { + actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND; + } else { + actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; + } + } else { + if (status.isRight() || status.left().value() == null) + actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES; + else { + actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE; + } + + } + String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service"; + responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName()); + } + return responseFormat; + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing certification request for resource {}", component.getUniqueId()); + + ActionStatus actionStatus; + ResponseFormat responseFormat; + Either result = null; + try{ + if (component.isTopologyTemplate()) { + + Either statusCert = validateAllResourceInstanceCertified(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } + + statusCert = validateConfiguredAtomicReqCapSatisfied(component); + if (statusCert.isRight()) { + return Either.right(statusCert.right().value()); + } + } + if (componentType == ComponentTypeEnum.SERVICE) { + + Either generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction); + + if (generateHeatEnvResult.isRight()) { + return Either.right(generateHeatEnvResult.right().value()); + } + Either generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction); + if (generateVfModuleResult.isRight()) { + return Either.right(generateVfModuleResult.right().value()); + } + component = generateVfModuleResult.left().value(); + + } + + Either, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock); + if (eitherPopulated != null && eitherPopulated.isRight()) { + return Either.right(eitherPopulated.right().value()); + } + + Either certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (certificationRequestResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = certificationRequestResult.right().value(); + actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (!inTransaction) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (!inTransaction) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + private Either validateConfiguredAtomicReqCapSatisfied(Component component) { + log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId()); + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + // Prepare relationships data structures + // Better make it list than set in case we need to count req/cap + // occurrences in the future + Map> reqName2Ids = new HashMap<>(); + Map> capName2Ids = new HashMap<>(); + Map> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert(); + Map> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert(); + for (ComponentInstance compInst : componentInstances) { + String compInstId = compInst.getUniqueId(); + OriginTypeEnum originType = compInst.getOriginType(); + if (originType == null) { + log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId()); + continue; + } + String compInstType = originType.getValue(); + // Validating configured requirements fulfilled + if (null != requirementsToFulfillBeforeCert) { + Set reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType); + if (reqToFulfillForType != null) { + for (String reqNameToFulfill : reqToFulfillForType) { + List reqNameList = reqName2Ids.get(reqNameToFulfill); + if (reqNameList == null || !reqNameList.contains(compInstId)) { + log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType); + ComponentTypeEnum componentType = component.getComponentType(); + String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement", + reqNameToFulfill, "fulfilled"); + return Either.right(responseFormat); + } + } + } + } + // Validating configured capabilities consumed + if (null != capabilitiesToConsumeBeforeCert) { + Set capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType); + if (capToConsumeForType != null) { + for (String capNameToConsume : capToConsumeForType) { + List capNameList = capName2Ids.get(capNameToConsume); + if (capNameList == null || !capNameList.contains(compInstId)) { + log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType); + ComponentTypeEnum componentType = component.getComponentType(); + String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase(); + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability", + capNameToConsume, "consumed"); + return Either.right(responseFormat); + } + } + } + } + } + } + log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId()); + return Either.left(true); + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // case of "atomic" checkin and certification request - modifier must be + // the owner + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + // other states + if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java index bfe51ded48..0d9631e6ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java @@ -20,8 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -43,106 +42,106 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class CheckinTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName()); - - public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CHECKIN; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CHECKIN_RESOURCE; - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - log.debug("start performing checkin for {} {}", componentType.name(), component.getUniqueId()); - - Either result = null; - try{ - Either checkinResourceResult = lifeCycleOperation. - checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - - if (checkinResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkinResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){ - action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION; - } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ - action = ActionStatus.COMPONENT_ALREADY_CERTIFIED; - } - ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CheckinTransition.class); + + public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CHECKIN; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CHECKIN_RESOURCE; + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + log.debug("start performing checkin for {} {}", componentType, component.getUniqueId()); + + Either result = null; + try{ + Either checkinResourceResult = lifeCycleOperation. + checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkinResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkinResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN; + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){ + action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION; + } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){ + action = ActionStatus.COMPONENT_ALREADY_CERTIFIED; + } + ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index b7983b1174..e5afcaeae5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -20,9 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -32,11 +30,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; @@ -49,148 +43,149 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; public class CheckoutTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); - - public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.CHECKOUT; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.CHECKOUT_RESOURCE; - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId()); - - Either result = null; - try { - - Either checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - - if (checkoutResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = checkoutResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } else { - - Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); - if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){ - Either upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); - if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ - result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); - return result; - } - if ( upgradeToLatestDerived.isLeft() ){ - //get resource after update derived - clonedComponent = upgradeToLatestDerived.left().value(); - } - } - result = Either.left(clonedComponent); - Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); - if (upgradeToLatestGeneric.isRight()) - result = Either.right(upgradeToLatestGeneric.right().value()); - else if (upgradeToLatestGeneric.left().value() ) { - StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); - if (StorageOperationStatus.OK != response) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - } - - } - - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { - - StorageOperationStatus updateStatus = StorageOperationStatus.OK; - Either updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); - if (updateEither.isRight()) - updateStatus = updateEither.right().value(); - else if (clonedComponent.shouldGenerateInputs()) { - List newInputs = clonedComponent.getInputs(); - updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME); - } - return updateStatus; - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // Disabled as of 1604 patch after discussing with Ella/Eli/Michael - - /* - * if (componentType == ComponentTypeEnum.PRODUCT){ Either productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } } - */ - - // check resource is not locked by another user - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { - if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - } - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class); + + public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.CHECKOUT; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.CHECKOUT_RESOURCE; + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing {} for resource {}", getName(), component.getUniqueId()); + + Either result = null; + try { + + Either checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + + if (checkoutResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = checkoutResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } else { + + Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); + if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){ + Either upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent); + if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){ + result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value())); + return result; + } + if ( upgradeToLatestDerived.isLeft() ){ + //get resource after update derived + clonedComponent = upgradeToLatestDerived.left().value(); + } + } + result = Either.left(clonedComponent); + Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); + if (upgradeToLatestGeneric.isRight()) + result = Either.right(upgradeToLatestGeneric.right().value()); + else if (upgradeToLatestGeneric.left().value() ) { + StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent); + if (StorageOperationStatus.OK != response) { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + } + + } + + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { + + StorageOperationStatus updateStatus = StorageOperationStatus.OK; + Either updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); + if (updateEither.isRight()) + updateStatus = updateEither.right().value(); + else if (clonedComponent.shouldGenerateInputs()) { + List newInputs = clonedComponent.getInputs(); + updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME); + } + return updateStatus; + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // Disabled as of 1604 patch after discussing with Ella/Eli/Michael + + /* + * if (componentType == ComponentTypeEnum.PRODUCT){ Either productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } } + */ + + // check resource is not locked by another user + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { + if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + } + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java index 87e8175960..4270295e36 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -45,130 +42,129 @@ import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class LifeCycleTransition { - protected ConfigurationManager configurationManager; - @Autowired - protected ToscaElementLifecycleOperation lifeCycleOperation; - @Autowired - protected TitanDao titanDao; - protected ComponentsUtils componentUtils; - - protected Map> authorizedRoles; - protected Map> resourceAuthorizedRoles; - - ToscaOperationFacade toscaOperationFacade; - - protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - - this.configurationManager = ConfigurationManager.getConfigurationManager(); - this.lifeCycleOperation = lifecycleOperation2; - this.componentUtils = componentUtils; - this.authorizedRoles = new HashMap<>(); - this.resourceAuthorizedRoles = new HashMap<>(); - this.toscaOperationFacade = toscaOperationFacade; - this.titanDao = titanDao; - } - - public abstract LifeCycleTransitionEnum getName(); - - public abstract AuditingActionEnum getAuditingAction(); - - public ConfigurationManager getConfigurationManager() { - return configurationManager; - } - - public void setConfigurationManager(ConfigurationManager configurationManager) { - this.configurationManager = configurationManager; - } - - public ToscaElementLifecycleOperation getLifeCycleOperation() { - return lifeCycleOperation; - } - - public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) { - this.lifeCycleOperation = lifeCycleOperation; - } - - public List getAuthorizedRoles(ComponentTypeEnum componentType) { - return authorizedRoles.get(componentType); - } - - public void addAuthorizedRoles(ComponentTypeEnum componentType, List authorizedRoles) { - this.authorizedRoles.put(componentType, authorizedRoles); - } - - public List getResourceAuthorizedRoles(ResourceTypeEnum resourceType) { - return resourceAuthorizedRoles.get(resourceType); - } - - public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List authorizedRoles) { - this.resourceAuthorizedRoles.put(resourceType, authorizedRoles); - } - - public abstract Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction); - - public abstract Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo); - - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) { - - return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null); - } - - /** - * getComponentOwner - * - * @param resource - * @return - */ - protected Either getComponentOwner(Component component, ComponentTypeEnum componentType) { - - return getComponentOwner(component, componentType, false); - } - - protected Either getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) { - - Either resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); - if (resourceOwnerResult.isRight()) { - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); - return Either.right(responseFormat); - } - return Either.left(resourceOwnerResult.left().value()); - } - - protected Either userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - - // validate user - //first check the user for the component and then for the resource - if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) { - return Either.left(true); - } - // this is only used in 2 cases - //1. when creating vfc/cp when import vf from csar - when we - // create resources from node type, we create need to change the state - // to certified - //2. certification flow upno upgrade migration - if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) { - return Either.left(true); - } - - ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - return Either.right(responseFormat); - } - - protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) { - if (componentType.equals(ComponentTypeEnum.RESOURCE)){ - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) { - return true; - } - } else { - return false; - } - - return false; - } + protected ConfigurationManager configurationManager; + @Autowired + protected ToscaElementLifecycleOperation lifeCycleOperation; + @Autowired + protected TitanDao titanDao; + protected ComponentsUtils componentUtils; + + protected Map> authorizedRoles; + protected Map> resourceAuthorizedRoles; + + ToscaOperationFacade toscaOperationFacade; + + protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + + this.configurationManager = ConfigurationManager.getConfigurationManager(); + this.lifeCycleOperation = lifecycleOperation2; + this.componentUtils = componentUtils; + this.authorizedRoles = new HashMap<>(); + this.resourceAuthorizedRoles = new HashMap<>(); + this.toscaOperationFacade = toscaOperationFacade; + this.titanDao = titanDao; + } + + public abstract LifeCycleTransitionEnum getName(); + + public abstract AuditingActionEnum getAuditingAction(); + + public ConfigurationManager getConfigurationManager() { + return configurationManager; + } + + public void setConfigurationManager(ConfigurationManager configurationManager) { + this.configurationManager = configurationManager; + } + + public ToscaElementLifecycleOperation getLifeCycleOperation() { + return lifeCycleOperation; + } + + public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) { + this.lifeCycleOperation = lifeCycleOperation; + } + + public List getAuthorizedRoles(ComponentTypeEnum componentType) { + return authorizedRoles.get(componentType); + } + + public void addAuthorizedRoles(ComponentTypeEnum componentType, List authorizedRoles) { + this.authorizedRoles.put(componentType, authorizedRoles); + } + + public List getResourceAuthorizedRoles(ResourceTypeEnum resourceType) { + return resourceAuthorizedRoles.get(resourceType); + } + + public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List authorizedRoles) { + this.resourceAuthorizedRoles.put(resourceType, authorizedRoles); + } + + public abstract Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction); + + public abstract Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo); + + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) { + + return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null); + } + + /** + * getComponentOwner + * + * @param resource + * @return + */ + protected Either getComponentOwner(Component component, ComponentTypeEnum componentType) { + + return getComponentOwner(component, componentType, false); + } + + protected Either getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) { + + Either resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId()); + if (resourceOwnerResult.isRight()) { + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType); + return Either.right(responseFormat); + } + return Either.left(resourceOwnerResult.left().value()); + } + + protected Either userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + + // validate user + //first check the user for the component and then for the resource + if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) { + return Either.left(true); + } + // this is only used in 2 cases + //1. when creating vfc/cp when import vf from csar - when we + // create resources from node type, we create need to change the state + // to certified + //2. certification flow upno upgrade migration + if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) { + return Either.left(true); + } + + ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + + protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) { + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) { + return true; + } + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java index e478bc6924..75b0bd934a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - +import fj.data.Either; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -33,7 +28,6 @@ import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; @@ -56,414 +50,399 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; @org.springframework.stereotype.Component("lifecycleBusinessLogic") public class LifecycleBusinessLogic { - private static final String COMMENT = "comment"; + private static final String COMMENT = "comment"; + + @Autowired + private IGraphLockOperation graphLockOperation = null; + + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @Autowired + private TitanDao titanDao; + + @Autowired + private CapabilityOperation capabilityOperation; + + private static final Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class); - @Autowired - private IGraphLockOperation graphLockOperation = null; + @javax.annotation.Resource + private ComponentsUtils componentUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; + @javax.annotation.Resource + private ToscaElementLifecycleOperation lifecycleOperation; + @javax.annotation.Resource + ArtifactsBusinessLogic artifactsManager; - @Autowired - private TitanDao titanDao; + @javax.annotation.Resource + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Autowired - private CapabilityOperation capabilityOperation; + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; - private static Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class.getName()); + @javax.annotation.Resource + private ResourceBusinessLogic resourceBusinessLogic; - @javax.annotation.Resource - private ComponentsUtils componentUtils; + @javax.annotation.Resource + private ProductBusinessLogic productBusinessLogic; - @javax.annotation.Resource - private ToscaElementLifecycleOperation lifecycleOperation; - @javax.annotation.Resource - ArtifactsBusinessLogic artifactsManager; - - @javax.annotation.Resource - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - @javax.annotation.Resource - private ResourceBusinessLogic resourceBusinessLogic; - - @javax.annotation.Resource - private ProductBusinessLogic productBusinessLogic; - - @Autowired - private ToscaExportHandler toscaExportUtils; - - @Autowired - ICacheMangerOperation cacheManagerOperation; - - @Autowired - ToscaOperationFacade toscaOperationFacade; - - private Map stateTransitions; - private static volatile boolean isInitialized = false; - - @PostConstruct - public void init() { - // init parameters - if (!isInitialized) { - synchronized (this) { - if (!isInitialized) { - initStateOperations(); - isInitialized = true; - } - } - } - } - - private void initStateOperations() { - stateTransitions = new HashMap(); - - LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(checkoutOp.getName().name(), checkoutOp); - - UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); - stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); - - LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(checkinOp.getName().name(), checkinOp); - - LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); - stateTransitions.put(certificationRequest.getName().name(), certificationRequest); - - LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(startCertification.getName().name(), startCertification); - - LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(failCertification.getName().name(), failCertification); - - LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - stateTransitions.put(cancelCertification.getName().name(), cancelCertification); - - CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - successCertification.setArtifactsManager(artifactsBusinessLogic); - stateTransitions.put(successCertification.getName().name(), successCertification); - } - - public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) { - return stateTransitions.get(transitionEnum.name()); - } - - public Either changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { - return (Either) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); - } - - // TODO: rhalili - should use changeComponentState when possible - public Either changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { - return (Either) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); - } - - private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){ - if (componentType.equals(ComponentTypeEnum.RESOURCE)){ - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (resourceType.equals(ResourceTypeEnum.VFCMT)){ - return true; - } - } - return false; - } - - public Either changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, - boolean needLock) { - - LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name()); - if (lifeCycleTransition == null) { - log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(error); - } - Component component = null; - log.info("get resource from graph"); - ResponseFormat errorResponse; - - Either eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo); - if (eitherResourceResponse.isRight()) { - return eitherResourceResponse; - } - component = eitherResourceResponse.left().value(); - String resourceCurrVersion = component.getVersion(); - LifecycleStateEnum resourceCurrState = component.getLifecycleState(); - - // lock resource - if (!inTransaction && needLock) { - log.info("lock component {}", componentId); - Either eitherLockResource = lockComponent(componentType, component); - if (eitherLockResource.isRight()) { - errorResponse = eitherLockResource.right().value(); - componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, null); - log.error("lock component {} failed", componentId); - return Either.right(errorResponse); - } - log.debug("after lock component {}", componentId); - } - try { - Either commentValidationResult = validateComment(changeInfo, transitionEnum); - if (commentValidationResult.isRight()) { - errorResponse = commentValidationResult.right().value(); - EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return Either.right(errorResponse); - } - changeInfo.setUserRemarks(commentValidationResult.left().value()); - log.debug("after validate component"); - Either validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); - if (validateHighestVersion.isRight()) { - return Either.right(validateHighestVersion.right().value()); - } - log.debug("after validate Highest Version"); - if (isComponentVFCMT(component,componentType)){ - Either changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component); - if (changeVFCMTStateResponse.isRight()){ - return changeVFCMTStateResponse; - } - } - - return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); - } finally { - component.setUniqueId(componentId); - if (!inTransaction && needLock) { - log.info("unlock component {}", componentId); - NodeTypeEnum nodeType = componentType.getNodeType(); - log.info("During change state, another component {} has been created/updated", componentId); - graphLockOperation.unlockComponent(componentId, nodeType); - - } - } - - } - - /* - * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin - * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400 - */ - private Either changeVFCMTState(ComponentTypeEnum componentType, User modifier, - LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, - Component component) { - LifecycleStateEnum oldState = component.getLifecycleState(); - if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) || - transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){ - return Either.right(componentUtils.getResponseFormat( - ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName())); - } //certify is done directly from checkin - else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){ - //we will call for submit for testing first and then for certify - Either actionResponse = changeState(component, - stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()), - componentType, modifier, changeInfo, inTransaction); - if (actionResponse.isRight()) { - return actionResponse; - } - actionResponse = changeState(component, - stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()), - componentType, modifier, changeInfo, inTransaction); - if (actionResponse.isRight()) { - return actionResponse; - } - } - return Either.left(null); - } - - private Either changeState(Component component, LifeCycleTransition lifeCycleTransition, - ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){ - ResponseFormat errorResponse; - - LifecycleStateEnum oldState = component.getLifecycleState(); - String resourceCurrVersion = component.getVersion(); - ComponentBusinessLogic bl = getComponentBL(componentType); - - Either ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); - if (ownerResult.isRight()) { - return Either.right(ownerResult.right().value()); - } - User owner = ownerResult.left().value(); - log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); - - Either stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); - if (stateValidationResult.isRight()) { - log.error("Failed to validateBeforeTransition"); - errorResponse = stateValidationResult.right().value(); - EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return Either.right(errorResponse); - } - - Either operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); - - if (operationResult.isRight()) { - errorResponse = operationResult.right().value(); - log.info("audit before sending error response"); - componentUtils.auditComponentAdmin(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); - - return Either.right(errorResponse); - } - Component resourceAfterOperation = operationResult.left().value(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - return operationResult; - - } - - private Either getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) { - - Either eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId); - - ResponseFormat errorResponse; - if (eitherResourceResponse.isRight()) { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); - errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); - log.debug("audit before sending response"); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentId); - componentUtils.auditComponent(errorResponse, modifier, null, Constants.EMPTY_STRING, Constants.EMPTY_STRING, lifeCycleTransition.getAuditingAction(), componentType, auditingFields); - - return Either.right(errorResponse); - } - return Either.left(eitherResourceResponse.left().value()); - } - - private Either validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { - ResponseFormat errorResponse; - if (!resource.isHighestVersion()) { - log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName()); - errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase()); - componentUtils.auditResource(errorResponse, modifier, resource, resource.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), null); - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either validateResourceNotDeleted(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { - - ResponseFormat errorResponse; - if ((resource.getIsDeleted() != null) && (resource.getIsDeleted() == true)) { - ActionStatus actionStatus = ActionStatus.RESOURCE_NOT_FOUND; - errorResponse = componentUtils.getResponseFormatByResource(actionStatus, resource.getName()); - log.debug("resource {} {} is marked for delete", resource.getName(), resource.getVersion()); - componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null); - - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) { - ResponseFormat errorResponse; - if (!component.isHighestVersion()) { - log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(), - component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase()); - componentUtils.auditComponentAdmin(errorResponse, modifier, component, component.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType); - return Either.right(errorResponse); - } - return Either.left(true); - } - - private Either lockComponent(ComponentTypeEnum componentType, Component component) { - NodeTypeEnum nodeType = componentType.getNodeType(); - StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType); - - if (lockResourceStatus.equals(StorageOperationStatus.OK)) { - return Either.left(true); - } else { - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus); - ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - return Either.right(responseFormat); - } - - } - - private Either validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { - String comment = changeInfo.getUserRemarks(); - if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum - || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum - // import? - ) { - - if (!ValidationUtils.validateStringNotEmpty(comment)) { - log.debug("user comment cannot be empty or null."); - ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT); - return Either.right(errorResponse); - } - - comment = ValidationUtils.removeNoneUtf8Chars(comment); - comment = ValidationUtils.removeHtmlTags(comment); - comment = ValidationUtils.normaliseWhitespace(comment); - comment = ValidationUtils.stripOctets(comment); - - if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) { - log.debug("user comment exceeds limit."); - return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); - } - if (!ValidationUtils.validateIsEnglish(comment)) { - return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - return Either.left(comment); - } - - private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) { - ComponentBusinessLogic businessLogic; - switch (componentTypeEnum) { - case RESOURCE: { - businessLogic = this.resourceBusinessLogic; - break; - } - case SERVICE: { - businessLogic = this.serviceBusinessLogic; - break; - } - case PRODUCT: { - businessLogic = this.productBusinessLogic; - break; - } - - default: { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); - throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); - } - } - return businessLogic; - } - - public Either getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) { - - Either latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid); - - if (latestVersionEither.isRight()) { - - return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid)); - } - - Component latestComponent = latestVersionEither.left().value(); - - return Either.left(latestComponent); - } + @Autowired + private ToscaExportHandler toscaExportUtils; + + @Autowired + ICacheMangerOperation cacheManagerOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; + + private Map stateTransitions; + private static volatile boolean isInitialized = false; + + @PostConstruct + public void init() { + // init parameters + if (!isInitialized) { + synchronized (this) { + if (!isInitialized) { + initStateOperations(); + isInitialized = true; + } + } + } + } + + private void initStateOperations() { + stateTransitions = new HashMap(); + + LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(checkoutOp.getName().name(), checkoutOp); + + UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic); + stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp); + + LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(checkinOp.getName().name(), checkinOp); + + LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); + stateTransitions.put(certificationRequest.getName().name(), certificationRequest); + + LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(startCertification.getName().name(), startCertification); + + LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(failCertification.getName().name(), failCertification); + + LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + stateTransitions.put(cancelCertification.getName().name(), cancelCertification); + + CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + successCertification.setArtifactsManager(artifactsBusinessLogic); + stateTransitions.put(successCertification.getName().name(), successCertification); + } + + public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) { + return stateTransitions.get(transitionEnum.name()); + } + + public Either changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { + return (Either) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); + } + + // TODO: rhalili - should use changeComponentState when possible + public Either changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) { + return (Either) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock); + } + + private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){ + if (componentType.equals(ComponentTypeEnum.RESOURCE)){ + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (resourceType.equals(ResourceTypeEnum.VFCMT)){ + return true; + } + } + return false; + } + + public Either changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, + boolean needLock) { + + LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name()); + if (lifeCycleTransition == null) { + log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); + ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier,componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(error); + } + Component component = null; + log.info("get resource from graph"); + ResponseFormat errorResponse; + + Either eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo); + if (eitherResourceResponse.isRight()) { + return eitherResourceResponse; + } + component = eitherResourceResponse.left().value(); + String resourceCurrVersion = component.getVersion(); + LifecycleStateEnum resourceCurrState = component.getLifecycleState(); + + // lock resource + if (!inTransaction && needLock) { + log.info("lock component {}", componentId); + Either eitherLockResource = lockComponent(componentType, component); + if (eitherLockResource.isRight()) { + errorResponse = eitherLockResource.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build()); + + log.error("lock component {} failed", componentId); + return Either.right(errorResponse); + } + log.debug("after lock component {}", componentId); + } + try { + Either commentValidationResult = validateComment(changeInfo, transitionEnum); + if (commentValidationResult.isRight()) { + errorResponse = commentValidationResult.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder() + .state(resourceCurrState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks()); + return Either.right(errorResponse); + } + changeInfo.setUserRemarks(commentValidationResult.left().value()); + log.debug("after validate component"); + Either validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType); + if (validateHighestVersion.isRight()) { + return Either.right(validateHighestVersion.right().value()); + } + log.debug("after validate Highest Version"); + if (isComponentVFCMT(component,componentType)){ + Either changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, true, component); + if (changeVFCMTStateResponse.isRight()){ + return changeVFCMTStateResponse; + } + component = changeVFCMTStateResponse.left().value(); + } + return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction); + } finally { + component.setUniqueId(componentId); + if (!inTransaction && needLock) { + log.info("unlock component {}", componentId); + NodeTypeEnum nodeType = componentType.getNodeType(); + log.info("During change state, another component {} has been created/updated", componentId); + graphLockOperation.unlockComponent(componentId, nodeType); + + } + } + + } + + /* + * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin + * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400 + */ + private Either changeVFCMTState(ComponentTypeEnum componentType, User modifier, + LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, + Component component) { + LifecycleStateEnum oldState = component.getLifecycleState(); + Component updatedComponent = component; + if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) || + transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){ + return Either.right(componentUtils.getResponseFormat( + ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName())); + } //certify is done directly from checkin + else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){ + //we will call for submit for testing first and then for certify + Either actionResponse = changeState(component, + stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; + } + updatedComponent = actionResponse.left().value(); + actionResponse = changeState(updatedComponent, + stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()), + componentType, modifier, changeInfo, inTransaction); + if (actionResponse.isRight()) { + return actionResponse; + } + updatedComponent = actionResponse.left().value(); + + } + return Either.left(updatedComponent); + } + + private Either changeState(Component component, LifeCycleTransition lifeCycleTransition, + ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){ + ResponseFormat errorResponse; + + LifecycleStateEnum oldState = component.getLifecycleState(); + String resourceCurrVersion = component.getVersion(); + ComponentBusinessLogic bl = getComponentBL(componentType); + + Either ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction); + if (ownerResult.isRight()) { + return Either.right(ownerResult.right().value()); + } + User owner = ownerResult.left().value(); + log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId()); + + Either stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo); + if (stateValidationResult.isRight()) { + log.error("Failed to validateBeforeTransition"); + errorResponse = stateValidationResult.right().value(); + componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().version(resourceCurrVersion).state(oldState.name()).build(), changeInfo.getUserRemarks()); + return Either.right(errorResponse); + } + + Either operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction); + + if (operationResult.isRight()) { + errorResponse = operationResult.right().value(); + log.info("audit before sending error response"); + componentUtils.auditComponentAdmin(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build()); + + return Either.right(errorResponse); + } + Component resourceAfterOperation = operationResult.left().value(); + componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks()); + return operationResult; + + } + + private Either getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) { + + Either eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId); + + ResponseFormat errorResponse; + if (eitherResourceResponse.isRight()) { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType); + errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING); + log.debug("audit before sending response"); + componentUtils.auditComponent(errorResponse, modifier, lifeCycleTransition.getAuditingAction(), componentId, componentType, changeInfo.getUserRemarks()); + + return Either.right(errorResponse); + } + return Either.left(eitherResourceResponse.left().value()); + } + + private Either validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) { + ResponseFormat errorResponse; + if (!resource.isHighestVersion()) { + log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName()); + errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase()); + componentUtils.auditResource(errorResponse, modifier, resource, lifeCycleTransition.getAuditingAction(), ResourceAuditData.newBuilder() + .state(resource.getLifecycleState().name()).version(resourceCurrVersion).build()); + return Either.right(errorResponse); + } + return Either.left(true); + } + + private Either validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) { + ResponseFormat errorResponse; + if (!component.isHighestVersion()) { + log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(), + component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase()); + componentUtils.auditComponentAdmin(errorResponse, modifier, component,lifeCycleTransition.getAuditingAction(), componentType, + ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(resourceCurrVersion).build()); + return Either.right(errorResponse); + } + return Either.left(true); + } + + private Either lockComponent(ComponentTypeEnum componentType, Component component) { + NodeTypeEnum nodeType = componentType.getNodeType(); + StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType); + + if (lockResourceStatus.equals(StorageOperationStatus.OK)) { + return Either.left(true); + } else { + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus); + ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + return Either.right(responseFormat); + } + + } + + private Either validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) { + String comment = changeInfo.getUserRemarks(); + if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum + || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum + // import? + ) { + + if (!ValidationUtils.validateStringNotEmpty(comment)) { + log.debug("user comment cannot be empty or null."); + ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT); + return Either.right(errorResponse); + } + + comment = ValidationUtils.removeNoneUtf8Chars(comment); + comment = ValidationUtils.removeHtmlTags(comment); + comment = ValidationUtils.normaliseWhitespace(comment); + comment = ValidationUtils.stripOctets(comment); + + if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) { + log.debug("user comment exceeds limit."); + return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH))); + } + if (!ValidationUtils.validateIsEnglish(comment)) { + return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + return Either.left(comment); + } + + private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) { + ComponentBusinessLogic businessLogic; + switch (componentTypeEnum) { + case RESOURCE: + businessLogic = this.resourceBusinessLogic; + break; + case SERVICE: + businessLogic = this.serviceBusinessLogic; + break; + case PRODUCT: + businessLogic = this.productBusinessLogic; + break; + default: + throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); + } + return businessLogic; + } + + public Either getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) { + + Either latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid); + + if (latestVersionEither.isRight()) { + + return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid)); + } + + Component latestComponent = latestVersionEither.left().value(); + + return Either.left(latestComponent); + } /** * Performs Force certification. * Note that a Force certification is allowed for the first certification only, @@ -476,59 +455,59 @@ public class LifecycleBusinessLogic { * @param needLock * @return */ - public Either forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { - Either result = null; - Either certifyResourceRes = null; - if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){ - log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction().name()); - result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - if(!isFirstCertification(resource.getVersion())){ - log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName()); - result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - // lock resource - if(result == null && !inTransaction && needLock){ - log.info("lock component {}", resource.getUniqueId()); - Either eitherLockResource = lockComponent(resource.getComponentType(), resource); - if (eitherLockResource.isRight()) { - log.error("lock component {} failed", resource.getUniqueId()); - result = Either.right(eitherLockResource.right().value()); - } - log.info("after lock component {}", resource.getUniqueId()); - } - try{ - if(result == null){ - certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion()); - if (certifyResourceRes.isRight()) { - StorageOperationStatus status = certifyResourceRes.right().value(); - log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status); - result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); - } - } - if(result == null){ - result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value())); - } - } finally { - log.info("unlock component {}", resource.getUniqueId()); - if (!inTransaction) { - if(result.isLeft()){ - titanDao.commit(); - } else{ - titanDao.rollback(); - } - if(needLock){ - NodeTypeEnum nodeType = resource.getComponentType().getNodeType(); - log.info("During change state, another component {} has been created/updated", resource.getUniqueId()); - graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType); - } - } - } - return result; - } - - public boolean isFirstCertification(String previousVersion) { - return previousVersion.split("\\.")[0].equals("0"); - } + public Either forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) { + Either result = null; + Either certifyResourceRes = null; + if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){ + log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction()); + result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + if(!isFirstCertification(resource.getVersion())){ + log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName()); + result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); + } + // lock resource + if(result == null && !inTransaction && needLock){ + log.info("lock component {}", resource.getUniqueId()); + Either eitherLockResource = lockComponent(resource.getComponentType(), resource); + if (eitherLockResource.isRight()) { + log.error("lock component {} failed", resource.getUniqueId()); + result = Either.right(eitherLockResource.right().value()); + } + log.info("after lock component {}", resource.getUniqueId()); + } + try{ + if(result == null){ + certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion()); + if (certifyResourceRes.isRight()) { + StorageOperationStatus status = certifyResourceRes.right().value(); + log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status); + result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource)); + } + } + if(result == null){ + result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value())); + } + } finally { + log.info("unlock component {}", resource.getUniqueId()); + if (!inTransaction) { + if(result.isLeft()){ + titanDao.commit(); + } else{ + titanDao.rollback(); + } + if(needLock){ + NodeTypeEnum nodeType = resource.getComponentType().getNodeType(); + log.info("During change state, another component {} has been created/updated", resource.getUniqueId()); + graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType); + } + } + } + return result; + } + + public boolean isFirstCertification(String previousVersion) { + return previousVersion.split("\\.")[0].equals("0"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java index 0c35caf41b..dcce9b002c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java @@ -22,21 +22,21 @@ package org.openecomp.sdc.be.components.lifecycle; public class LifecycleChangeInfoBase { - public LifecycleChangeInfoBase() { - } + public LifecycleChangeInfoBase() { + } - public LifecycleChangeInfoBase(String userRemarks) { - super(); - this.userRemarks = userRemarks; - } + public LifecycleChangeInfoBase(String userRemarks) { + super(); + this.userRemarks = userRemarks; + } - private String userRemarks; + private String userRemarks; - public String getUserRemarks() { - return userRemarks; - } + public String getUserRemarks() { + return userRemarks; + } - public void setUserRemarks(String userRemarks) { - this.userRemarks = userRemarks; - } + public void setUserRemarks(String userRemarks) { + this.userRemarks = userRemarks; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java index 5d8b29ecdc..51ec61ea6b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java @@ -22,29 +22,29 @@ package org.openecomp.sdc.be.components.lifecycle; public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase { - public enum LifecycleChanceActionEnum { - CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION - }; + public enum LifecycleChanceActionEnum { + CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION + }; - private LifecycleChanceActionEnum action; + private LifecycleChanceActionEnum action; - public LifecycleChangeInfoWithAction() { - } + public LifecycleChangeInfoWithAction() { + } - public LifecycleChangeInfoWithAction(String userRemarks) { - super(userRemarks); - } + public LifecycleChangeInfoWithAction(String userRemarks) { + super(userRemarks); + } - public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) { - super(userRemarks); - this.action = action; - } + public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) { + super(userRemarks); + this.action = action; + } - public LifecycleChanceActionEnum getAction() { - return action; - } + public LifecycleChanceActionEnum getAction() { + return action; + } - public void setAction(LifecycleChanceActionEnum action) { - this.action = action; - } + public void setAction(LifecycleChanceActionEnum action) { + this.action = action; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java index b74ae5d8e5..4dddc044f2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java @@ -48,97 +48,97 @@ import fj.data.Either; public class StartCertificationTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName()); - - public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles)); - // TODO to be later defined for product - - //additional authorized roles for resource type - Role[] resourceRoles = { Role.DESIGNER}; - addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.START_CERTIFICATION; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.START_CERTIFICATION_RESOURCE; - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - log.debug("start performing certification test for resource {}", component.getUniqueId()); - Either result = null; - try{ - Either stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); - if (stateChangeResult.isRight()) { - log.debug("start certification failed on graph"); - StorageOperationStatus response = stateChangeResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - - if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { - actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; - } - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); - if (inTransaction == false) { - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } - } else { - if (inTransaction == false) { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - } - return result; - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } + private static final Logger log = LoggerFactory.getLogger(StartCertificationTransition.class); + + public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles)); + // TODO to be later defined for product + + //additional authorized roles for resource type + Role[] resourceRoles = { Role.DESIGNER}; + addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles)); + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.START_CERTIFICATION; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.START_CERTIFICATION_RESOURCE; + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + log.debug("start performing certification test for resource {}", component.getUniqueId()); + Either result = null; + try{ + Either stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId()); + if (stateChangeResult.isRight()) { + log.debug("start certification failed on graph"); + StorageOperationStatus response = stateChangeResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + + if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) { + actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST; + } + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState"); + if (inTransaction == false) { + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } + } else { + if (inTransaction == false) { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + } + return result; + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFIED)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java index 324e46016f..9444faa27a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import java.util.Arrays; +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; @@ -44,97 +44,97 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.Arrays; public class UndoCheckoutTransition extends LifeCycleTransition { - private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName()); - private ArtifactsBusinessLogic artifactsManager; - - public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { - super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); - - // authorized roles - Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; - Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; - addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); - addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); - - } - - @Override - public LifeCycleTransitionEnum getName() { - return LifeCycleTransitionEnum.UNDO_CHECKOUT; - } - - @Override - public AuditingActionEnum getAuditingAction() { - return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE; - } - - public ArtifactsBusinessLogic getArtifactsBusinessLogic() { - return artifactsManager; - } - - public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) { - this.artifactsManager = artifactsBusinessLogic; - } - - @Override - public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { - String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); - - // validate user - Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); - if (userValidationResponse.isRight()) { - return userValidationResponse; - } - - // check resource is not locked by another user - if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { - ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); - return Either.right(error); - } - - return Either.left(true); - } - - @Override - public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { - - Either result = null; - log.debug("start performing undo-checkout for resource {}", component.getUniqueId()); - - try { - Either undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId()); - - if (undoCheckoutResourceResult.isRight()) { - log.debug("checkout failed on graph"); - StorageOperationStatus response = undoCheckoutResourceResult.right().value(); - ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); - ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); - result = Either.right(responseFormat); - } - else { - result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value())); - } - } finally { - if (result == null || result.isRight()) { - BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); - log.debug("operation failed. do rollback"); - titanDao.rollback(); - } else { - log.debug("operation success. do commit"); - titanDao.commit(); - } - } - return result; - } + private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class); + private ArtifactsBusinessLogic artifactsManager; + + public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) { + super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao); + + // authorized roles + Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER }; + Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER }; + addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles)); + addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles)); + + } + + @Override + public LifeCycleTransitionEnum getName() { + return LifeCycleTransitionEnum.UNDO_CHECKOUT; + } + + @Override + public AuditingActionEnum getAuditingAction() { + return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE; + } + + public ArtifactsBusinessLogic getArtifactsBusinessLogic() { + return artifactsManager; + } + + public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) { + this.artifactsManager = artifactsBusinessLogic; + } + + @Override + public Either validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) { + String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId()); + + // validate user + Either userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo); + if (userValidationResponse.isRight()) { + return userValidationResponse; + } + + // check resource is not locked by another user + if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) { + ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId()); + return Either.right(error); + } + + return Either.left(true); + } + + @Override + public Either changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) { + + Either result = null; + log.debug("start performing undo-checkout for resource {}", component.getUniqueId()); + + try { + Either undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId()); + + if (undoCheckoutResourceResult.isRight()) { + log.debug("checkout failed on graph"); + StorageOperationStatus response = undoCheckoutResourceResult.right().value(); + ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response); + ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); + result = Either.right(responseFormat); + } + else { + result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value())); + } + } finally { + if (result == null || result.isRight()) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph"); + log.debug("operation failed. do rollback"); + titanDao.rollback(); + } else { + log.debug("operation success. do commit"); + titanDao.commit(); + } + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java index 9c140b36c7..e6dd6457cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java @@ -1,9 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -12,7 +9,9 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; @Component public class GlobalInputsFilteringBusinessLogic extends BaseBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java index eb359e949e..4bd799805f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -11,7 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; @Component public class GlobalTypesMergeBusinessLogic implements MergeResourceBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java index 6c20e501f9..058d4c2555 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; import org.springframework.stereotype.Component; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @Component public class RelationsComparator { @@ -45,8 +45,8 @@ public class RelationsComparator { private boolean findRelation(Resource oldResource, List oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) { for (RequirementCapabilityRelDef oldRelation : oldRelations) { - RelationshipInfo oldRelationship = oldRelation.getSingleRelationship().getRelation(); - RelationshipInfo newRelationship = newRelation.getSingleRelationship().getRelation(); + RelationshipInfo oldRelationship = oldRelation.resolveSingleRelationship().getRelation(); + RelationshipInfo newRelationship = newRelation.resolveSingleRelationship().getRelation(); if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) { return true; } @@ -70,12 +70,12 @@ public class RelationsComparator { private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){ - return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); + return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid()); } else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){ - return true; + return true; } - return false; + return false; } private boolean isRelationshipTypeEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { @@ -84,12 +84,12 @@ public class RelationsComparator { private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) { if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){ - return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); + return oldRelationship.getRequirement().equals(newRelationship.getRequirement()); } else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){ - return true; + return true; } - return false; + return false; } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java index 8b48b0897a..0f68f9f409 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.exception.SdcActionException; @@ -15,7 +13,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component public class TopologyComparator { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java new file mode 100644 index 0000000000..0a467ef876 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +import java.util.List; +import java.util.Map; + +public interface CapabilityResolver { + + /** + * + * @param container the instance container + * @param prevInstanceOrigNode the prev instance's original node type + * @param cmptInstanceId the current instance id + * @param prevCapabilities list of previous capabilities for which to find their corresponding new capabilities + * @return a mapping between the prev capability to its corresponding new capability (if exists) + */ + Map resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List prevCapabilities); + + /** + * + * @param oldInstance the old instance of which its capabilities are to be mapped as the key + * @param currInstance the curr instance of which its capabilities are to be mapped as the value + * @return a mapping between the prev capability to its corresponding new capability (if exists) + */ + Map resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance); +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java new file mode 100644 index 0000000000..8400b32f9b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java @@ -0,0 +1,82 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component +public class SimpleCapabilityResolver implements CapabilityResolver { + + private MergeInstanceUtils mergeInstanceUtils; + + public SimpleCapabilityResolver(MergeInstanceUtils mergeInstanceUtils) { + this.mergeInstanceUtils = mergeInstanceUtils; + } + + @Override + public Map resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List prevCapabilities) { + Map> newCapabilitiesByType = resolveInstanceCapabilities(container, cmptInstanceId).getCapabilities(); + Map oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, prevCapabilities); + return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner); + } + + @Override + public Map resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance) { + Map> newCapabilitiesByType = currInstance.getCapabilities(); + Map oldCapOwnerToNewOwner = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance); + List prevCapabilities = oldInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner); + } + + private Map mapOldToNewCapabilities(List prevCapabilities, Map> newCapabilitiesByType, Map oldCapOwnerToNewOwner) { + Map oldToNewCapability = prevCapabilities + .stream() + .collect(HashMap::new, + (resultMap, prevCap) -> mapOldToNewCapability(newCapabilitiesByType, oldCapOwnerToNewOwner, resultMap, prevCap), + HashMap::putAll); + removeNotFoundNewCapabilities(oldToNewCapability); + return oldToNewCapability; + } + + private CapabilityDefinition mapOldToNewCapability(Map> newCapabilitiesByType, Map oldCapOwnerToNewOwner, Map resultMap, CapabilityDefinition prevCap) { + return resultMap.put(prevCap, findCurrCapability(newCapabilitiesByType, prevCap, oldCapOwnerToNewOwner.get(prevCap.getOwnerId()))); + } + + private Map mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, List prevCapabilities) { + List prevCapOwnerIds = prevCapabilities.stream().map(CapabilityDefinition::getOwnerId).distinct().collect(Collectors.toList()); + return mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, origInstanceNode, cmptInstanceId, prevCapOwnerIds); + } + + private void removeNotFoundNewCapabilities(Map oldToNewCapMap) { + oldToNewCapMap.values().removeIf(Objects::isNull); + } + + private ComponentInstance resolveInstanceCapabilities(Component capabilityOwnerContainer, String cmptInstanceId) { + return MapUtil.toMap(capabilityOwnerContainer.getComponentInstances(), ComponentInstance::getUniqueId).get(cmptInstanceId); + } + + + private CapabilityDefinition findCurrCapability(Map> capabilitiesByType, CapabilityDefinition oldCap, String newCapOwnerId) { + List newCapOfType = capabilitiesByType.get(oldCap.getType()); + if (newCapOwnerId == null || CollectionUtils.isEmpty(newCapOfType)) { + return null; + } + return newCapOfType.stream().filter(sameNameAndOwner(oldCap.getName(), newCapOwnerId)) + .findFirst().orElse(null); + + } + + private Predicate sameNameAndOwner(String capName, String newCapOwnerId) { + return newCap -> newCap.getName().equals(capName) && newCap.getOwnerId().equals(newCapOwnerId); + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java index 1e1bc862cf..82deee598d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge.heat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * Created by chaya on 9/14/2017. */ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java index b8ea5e35c4..be5e5367b8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java @@ -1,9 +1,7 @@ package org.openecomp.sdc.be.components.merge.input; -import java.util.Collections; -import java.util.List; -import java.util.Map; - +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -12,10 +10,13 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component -public class ComponentInputsMergeBL { +public class ComponentInputsMergeBL implements ComponentsMergeCommand { @javax.annotation.Resource private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic; @@ -26,6 +27,17 @@ public class ComponentInputsMergeBL { @javax.annotation.Resource private ComponentsUtils componentsUtils; + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + List inputsToMerge = currentComponent.getInputs() != null ? currentComponent.getInputs() : new ArrayList<>(); + return this.mergeAndRedeclareComponentInputs(prevComponent, currentComponent, inputsToMerge); + } + + @Override + public String description() { + return "merge component inputs"; + } + public ActionStatus mergeAndRedeclareComponentInputs(Component prevComponent, Component newComponent, List inputsToMerge) { mergeInputs(prevComponent, inputsToMerge); List previouslyDeclaredInputs = inputsValuesMergingBusinessLogic.getPreviouslyDeclaredInputsToMerge(prevComponent, newComponent); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java index e49d2b2c87..e0e7947226 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java @@ -1,12 +1,5 @@ package org.openecomp.sdc.be.components.merge.input; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; @@ -14,6 +7,9 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.*; +import java.util.stream.Collectors; + @org.springframework.stereotype.Component public class InputsValuesMergingBusinessLogic { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java new file mode 100644 index 0000000000..e7117a2aeb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java @@ -0,0 +1,103 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.merge.capability.CapabilityResolver; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class ComponentCapabilitiesPropertiesMergeBL implements ComponentsMergeCommand { + + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentCapabilitiesPropertiesMergeBL.class); + + private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; + private ToscaOperationFacade toscaOperationFacade; + private ComponentsUtils componentsUtils; + private CapabilityResolver capabilityResolver; + + public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, CapabilityResolver capabilityResolver) { + this.dataDefinitionsValuesMergingBusinessLogic = dataDefinitionsValuesMergingBusinessLogic; + this.toscaOperationFacade = toscaOperationFacade; + this.componentsUtils = componentsUtils; + this.capabilityResolver = capabilityResolver; + } + + @Override + public String description() { + return "merge component instances capabilities properties"; + } + + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + StorageOperationStatus mergeStatus = getCmptWithCapabilitiesProps(currentComponent.getUniqueId()) + .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap), + err -> err); + return componentsUtils.convertFromStorageResponse(mergeStatus); + } + + public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId, List prevInstanceCapabilities) { + if (CollectionUtils.isEmpty(prevInstanceCapabilities)) { + return ActionStatus.OK; + } + Map oldToNewCap = capabilityResolver.resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities); + oldToNewCap.forEach(this::mergeCapabilityProperties); + StorageOperationStatus updateStatus = updateInstanceCapabilitiesProperties(currentComponent, instanceId); + return componentsUtils.convertFromStorageResponse(updateStatus); + } + + private StorageOperationStatus mergeCmptCalculatedCapabilitiesProperties(Component prevComponent, Component currentComponent) { + List prevInstances = prevComponent.getComponentInstances(); + if (prevInstances == null) { + return StorageOperationStatus.OK; + } + prevInstances.forEach(prevInstance -> mergeInstanceCapabilities(prevInstance, currentComponent)); + return updateComponentCapabilitiesProperties(currentComponent); + } + + private void mergeInstanceCapabilities(ComponentInstance prevInstance, Component currComponent) { + ComponentInstance currInstance = MapUtil.toMap(currComponent.getComponentInstances(), ComponentInstance::getName).get(prevInstance.getName()); + Map oldToNewCapabilities = capabilityResolver.resolvePrevCapIdToNewCapability(prevInstance, currInstance); + oldToNewCapabilities.forEach(this::mergeCapabilityProperties); + } + + private void mergeCapabilityProperties(CapabilityDefinition prevCapability, CapabilityDefinition currCapability) { + dataDefinitionsValuesMergingBusinessLogic.mergeInstanceDataDefinitions(prevCapability.getProperties(), currCapability.getProperties()); + } + + private StorageOperationStatus updateComponentCapabilitiesProperties(Component currComponent) { + return toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currComponent); + } + + private StorageOperationStatus updateInstanceCapabilitiesProperties(Component currComponent, String instanceId) { + return toscaOperationFacade.updateComponentInstanceCapabilityProperties(currComponent, instanceId); + } + + private Either getCmptWithCapabilitiesProps(String cmptId) { + ComponentParametersView propertiesCapabilitiesFilter = new ComponentParametersView(true); + propertiesCapabilitiesFilter.setIgnoreCapabiltyProperties(false); + propertiesCapabilitiesFilter.setIgnoreComponentInstances(false); + propertiesCapabilitiesFilter.setIgnoreCapabilities(false); + return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter) + .right() + .map(err -> { + LOGGER.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err); + return err; + }); + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java index cac8c977e3..d16fa251e2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java @@ -1,10 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -16,7 +12,10 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; /** * Created by chaya on 9/20/2017. @@ -81,7 +80,7 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, jsonForUpdateArtifact, artifactsBusinessLogic.new ArtifactOperationInfo( - false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Link), currentArtifactDefinition.getValue()); + false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue()); if (uploadArtifactToService.isRight()) { return Either.right(uploadArtifactToService.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java new file mode 100644 index 0000000000..afad19baf2 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java @@ -0,0 +1,47 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.MapUtils.isNotEmpty; + +@org.springframework.stereotype.Component +public class ComponentInstanceCapabiliteisPropertiesMerge implements ComponentInstanceMergeInterface { + + private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; + private ComponentsUtils componentsUtils; + + public ComponentInstanceCapabiliteisPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, ComponentsUtils componentsUtils) { + this.capabilitiesPropertiesMergeBL = capabilitiesPropertiesMergeBL; + this.componentsUtils = componentsUtils; + } + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); + dataHolder.setOrigInstanceNode(originComponent); + } + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Component origInstanceNode = dataHolder.getOrigInstanceNode(); + List origInstanceCapabilities = dataHolder.getOrigInstanceCapabilities(); + ActionStatus mergeStatus = capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities); + return Either.iif(!ActionStatus.OK.equals(mergeStatus), () -> componentsUtils.getResponseFormat(mergeStatus), () -> updatedContainerComponent); + } + + private List getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { + return isNotEmpty( currentResourceInstance.getCapabilities() ) ? currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) : new ArrayList<>() ; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java new file mode 100644 index 0000000000..20a5abc591 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java @@ -0,0 +1,113 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.javatuples.Pair; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@org.springframework.stereotype.Component +public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMergeInterface { + + private static Logger log = LoggerFactory.getLogger(ComponentInstanceForwardingPathMerge.class); + + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + @Autowired + private ComponentsUtils componentsUtils; + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, + ComponentInstance currentResourceInstance, Component originComponent) { + dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance)); + dataHolder.setOrigInstanceNode(originComponent); + dataHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId()); + } + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, + Component updatedContainerComponent, String newInstanceId) { + if (!(updatedContainerComponent instanceof Service)) { + // no need to handle forwarding paths + return Either.left(updatedContainerComponent); + } + Service service = (Service) updatedContainerComponent; + ComponentInstance ci = service.getComponentInstanceById(newInstanceId).orElse(null); + if (ci == null){ + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, newInstanceId); + return Either.right(responseFormat); + } + Either resourceEither = toscaOperationFacade.getToscaFullElement(ci.getComponentUid()); + if (resourceEither.isRight() ) { + log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value())); + return Either.right(responseFormat); + } + + Component fetchedComponent = resourceEither.left().value(); + + Pair, Map> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service, dataHolder, fetchedComponent, newInstanceId); + Map updated = pair.getValue0(); + Map deleted = pair.getValue1(); + if (deleted != null && !deleted.isEmpty()) { + Either, ResponseFormat> deleteEither = serviceBusinessLogic + .deleteForwardingPaths(service.getUniqueId(), new HashSet<>(deleted.keySet()), user, false); + if (deleteEither.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Failed to delete forwarding paths : {}", deleted.values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )"))); + } + return Either.right(deleteEither.right().value()); + } + deleted.keySet().forEach(key -> service.getForwardingPaths().remove(key)); + } + if (updated != null && !updated.isEmpty()) { + Service updateFPService = new Service(); + updateFPService.setForwardingPaths(updated); + Either updateFPEither = serviceBusinessLogic + .updateForwardingPath(service.getUniqueId(), updateFPService, user, false); + if (updateFPEither.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Failed to update forwarding paths : {}", updated.values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )"))); + } + return Either.right(updateFPEither.right().value()); + } + updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key,forwardingPathDataDefinition)); + } + return Either.left(updatedContainerComponent); + } + + + private List getAllInstanceCapabilities(ComponentInstance currentResourceInstance) { + return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream) + .collect(Collectors.toList()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java index 1561cdc797..3938281ad2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java @@ -1,8 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -17,7 +15,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.List; +import java.util.Map; /** * Created by chaya on 9/20/2017. @@ -25,7 +24,7 @@ import fj.data.Either; @org.springframework.stereotype.Component("ComponentInstanceHeatEnvMerge") public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class); @Autowired private ArtifactsBusinessLogic artifactsBusinessLogic; @@ -52,7 +51,7 @@ public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInte Map json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null); Either, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json, - artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update), null); + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE), null); if (uploadArtifactToService.isRight()) { log.error("Failed to update artifact {} on resourceInstance {}", artifactInfo.getArtifactLabel(), newInstanceId); return Either.right(uploadArtifactToService.right().value()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java new file mode 100644 index 0000000000..2e289456e6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java @@ -0,0 +1,77 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class ComponentInstanceInputsMergeBL implements ComponentsMergeCommand { + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; + + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + Map> componentInstancesInputs = currentComponent.getComponentInstancesInputs(); + if (componentInstancesInputs == null) { + return ActionStatus.OK; + } + componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs)); + return updateComponentInstancesInputs(currentComponent, componentInstancesInputs); + } + + @Override + public String description() { + return "merge component instance inputs"; + } + + public ActionStatus mergeComponentInstanceInputs(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + List newInstInput = newComponent.safeGetComponentInstanceInput(instanceId); + if (newInstInput == null) { + return ActionStatus.OK; + } + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstInput, newComponent.getInputs()); + return updateComponentInstanceInputs(newComponent, instanceId, newInstInput); + } + + private ActionStatus updateComponentInstanceInputs(Component newComponent, String instanceId, List newInstInput) { + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceInputs(newComponent, instanceId, newInstInput); + if (storageOperationStatus != StorageOperationStatus.OK) { + return componentsUtils.convertFromStorageResponse(storageOperationStatus); + } + return ActionStatus.OK; + } + + private ActionStatus updateComponentInstancesInputs(Component component, Map> componentInstancesInputs) { + Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId()); + if (mapStorageOperationStatusEither.isRight()) { + return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); + } + return ActionStatus.OK; + } + + private void mergeOldInstanceInputsValues(Component oldComponent, Component newComponent, String instanceId, List instInputs) { + ComponentInstance currentCompInstance = newComponent.getComponentInstanceById(instanceId).get(); + List oldInstInputs = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceInputsByName(currentCompInstance.getName()); + List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs()); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java index 04af6b7fc0..d17469a287 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; @@ -15,14 +14,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.List; /** * Created by chaya on 9/12/2017. */ @org.springframework.stereotype.Component("componentInstanceMergeDataBusinessLogic") public class ComponentInstanceMergeDataBusinessLogic { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class); @Autowired private List componentInstancesMergeBLs; @@ -60,7 +59,7 @@ public class ComponentInstanceMergeDataBusinessLogic { */ public Either mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) { - Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); + Either componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { log.error("Component with id {} was not found", newContainerComponentId); StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value(); @@ -79,12 +78,15 @@ public class ComponentInstanceMergeDataBusinessLogic { return Either.left(updatedContainerComponent); } - private Either getComponentWithInstancesInputsAndProperties(String containerComponentId) { + private Either getComponentWithInstancesMergeEntities(String containerComponentId) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); filter.setIgnoreComponentInstancesInputs(false); filter.setIgnoreComponentInstancesProperties(false); + filter.setIgnoreCapabilities(false); + filter.setIgnoreCapabiltyProperties(false); filter.setIgnoreArtifacts(false); + filter.setIgnoreForwardingPath(false); return toscaOperationFacade.getToscaElement(containerComponentId, filter); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java index 1d2849b94c..f4bcfdab5c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java @@ -1,12 +1,11 @@ package org.openecomp.sdc.be.components.merge.instance; +import fj.data.Either; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; - /** * Created by chaya on 9/20/2017. */ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java new file mode 100644 index 0000000000..99b1d389ed --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class ComponentInstancePropertiesMergeBL implements ComponentsMergeCommand { + + @javax.annotation.Resource + private ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource(name = "componentUtils") + private ComponentsUtils componentsUtils; + + @javax.annotation.Resource + private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; + + @Override + public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) { + Map> newInstProps = currentComponent.getComponentInstancesProperties(); + if (newInstProps == null) { + return ActionStatus.OK; + } + newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(prevComponent, currentComponent, instanceId, newProps) ); + return updateComponentInstancesProperties(currentComponent, newInstProps); + } + + @Override + public String description() { + return "merge component instance properties"; + } + + + public ActionStatus mergeComponentInstanceProperties(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { + List newInstProps = newComponent.safeGetComponentInstanceProperties(instanceId); + if (newInstProps == null) { + return ActionStatus.OK; + } + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstProps, newComponent.getInputs()); + return updateComponentInstanceProperties(newComponent, instanceId, newInstProps); + } + + private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId, List newProps) { + List oldInstProperties = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId); + List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); + propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProperties, oldInputs, newProps, newComponent.getInputs()); + } + + private ActionStatus updateComponentInstancesProperties(Component newComponent, Map> newInstProps) { + Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId()); + if (mapStorageOperationStatusEither.isRight()) { + return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); + } + return ActionStatus.OK; + } + + private ActionStatus updateComponentInstanceProperties(Component component, String instanceId, List newInstProps) { + StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceProperties(component, instanceId, newInstProps); + if (storageOperationStatus != StorageOperationStatus.OK) { + return componentsUtils.convertFromStorageResponse(storageOperationStatus); + } + return ActionStatus.OK; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java index 765ddb57f6..b63cc38690 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java @@ -1,20 +1,10 @@ package org.openecomp.sdc.be.components.merge.instance; -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; @@ -22,7 +12,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; /** * Created by chaya on 9/20/2017. @@ -30,7 +21,7 @@ import fj.data.Either; @org.springframework.stereotype.Component("ComponentInstancePropsAndInputsMerge") public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface { - private static Logger log = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class); @Autowired private ToscaOperationFacade toscaOperationFacade; @@ -81,19 +72,19 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId); if (actionStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps); + LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps); return Either.right(actionStatus); } return Either.left(newComponentInstancesProps); } private Either, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) { - List originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); + List originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs(); List originComponentsInputs = dataHolder.getOrigComponentInputs(); List newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId); ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId); if (actionStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs); + LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs); return Either.right(actionStatus); } return Either.left(newComponentInstancesInputs); @@ -106,14 +97,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe // get instance inputs and properties after merge Either componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId); if (componentWithInstancesInputsAndProperties.isRight()) { - log.error("Component %s was not found", newContainerComponentId); + LOGGER.error("Component %s was not found", newContainerComponentId); return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value())); } Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value(); ActionStatus redeclareStatus = resourceInputsMergeBL.redeclareComponentInputsForInstance(origComponentInputs, updatedContainerComponent, newInstanceId); if (redeclareStatus != ActionStatus.OK) { - log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); + LOGGER.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer); Either.right(redeclareStatus); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java new file mode 100644 index 0000000000..96f878abe0 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java @@ -0,0 +1,416 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.aft.dme2.internal.google.common.annotations.VisibleForTesting; + +import fj.data.Either; + + +@org.springframework.stereotype.Component("ComponentInstanceRelashionMerge") +public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInterface { + private static Logger log = LoggerFactory.getLogger(ComponentInstanceRelationMerge.class); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + private MergeInstanceUtils mergeInstanceUtils; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + + @Override + public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) { + //All Relationships - container (service) holds info about all relations + //Filter by UniqueId in from/to + List relationsFrom = getRelations(RequirementCapabilityRelDef::getFromNode, + containerComponent, + currentResourceInstance); + + List relationsTo = getRelations(RequirementCapabilityRelDef::getToNode, + containerComponent, + currentResourceInstance); + + if (!relationsFrom.isEmpty() || !relationsTo.isEmpty()) { + List vfcInstances = mergeInstanceUtils.getVfcInstances(currentResourceInstance, originComponent); + + if (vfcInstances != null) { + List fromRelInfoList = convert(relationsFrom, rel -> mapRelationRequirement(rel, vfcInstances)); + List toRelInfoList = convert(relationsTo, rel -> mapRelationCapability(rel, vfcInstances)); + + // Encapsulate all needed info in one container + VfRelationsMergeInfo vfRelationsMergeInfo = new VfRelationsMergeInfo(fromRelInfoList, toRelInfoList); + // Save it + dataHolder.setVfRelationsInfo(vfRelationsMergeInfo); + } + } + else { + log.debug("No relations relevant to currentResourceInstance {} found in container component", currentResourceInstance); + } + + } + + + @Override + public Either mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) { + Wrapper> resultWrapper = new Wrapper<>(); + + VfRelationsMergeInfo vfRelationsMergeInfo = getRelationsMergeInfo(dataHolder, updatedContainerComponent, resultWrapper); + + ComponentInstance newComponentInstance = null; + if(resultWrapper.isEmpty()) { + //Component Instance + newComponentInstance = loadComponentInstance(updatedContainerComponent, newInstanceId, resultWrapper); + } + + if(resultWrapper.isEmpty() && vfRelationsMergeInfo != null) { + // Load VFCI and filter them by name + List vfcInstances = mergeInstanceUtils.getVfcInstances(newComponentInstance); + if(vfcInstances != null) { + Map vfciMap = mergeInstanceUtils.convertToVfciNameMap(vfcInstances); + + // Process Relationships + List toRelationsInfo = vfRelationsMergeInfo.getToRelationsInfo(); + Stream toRelationsInfoStream = null; + if (toRelationsInfo != null) { + toRelationsInfoStream = toRelationsInfo.stream() + .map(oldCapInfo -> restoreCapabilityRelation(oldCapInfo, newInstanceId, vfciMap, updatedContainerComponent)) + .filter(Objects::nonNull); + } + + List fromRelationsInfo = vfRelationsMergeInfo.getFromRelationsInfo(); + Stream fromRelationsInfoStream = null; + if( fromRelationsInfo != null) { + //For Each old requirement relation info + fromRelationsInfoStream = fromRelationsInfo.stream() + .map(oldReqInfo -> restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent)) + .filter(Objects::nonNull); + } + + // Save relations in updated container (service) + List updatedRelations = getUpdatedRelations(toRelationsInfoStream, fromRelationsInfoStream); + StorageOperationStatus saveResult = toscaOperationFacade.associateResourceInstances(updatedContainerComponent.getUniqueId(), updatedRelations); + if (saveResult == StorageOperationStatus.OK) { + resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); + } + else { + log.debug("Failed to associate instances of resource {} status is {}", updatedContainerComponent.getUniqueId(), saveResult); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(saveResult), updatedContainerComponent.getUniqueId()); + resultWrapper.setInnerElement(Either.right(responseFormat)); + } + } + } + + return resultWrapper.getInnerElement(); + } + + @VisibleForTesting + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + + @VisibleForTesting + public void setComponentsUtils(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @VisibleForTesting + public void setMergeInstanceUtils(MergeInstanceUtils mergeInstanceUtils) { + this.mergeInstanceUtils = mergeInstanceUtils; + } + + /** + * @param containerComponent + * @param instanceId + * @param resultWrapper + * @return + */ + private ComponentInstance loadComponentInstance(Component containerComponent, String instanceId, + Wrapper> resultWrapper) { + ComponentInstance componentInstance = containerComponent.getComponentInstanceById(instanceId).orElse(null); + if (componentInstance == null) { + log.debug("Failed to get VF instance by new VF instance ID: {}", instanceId); + resultWrapper.setInnerElement(Either.left(containerComponent)); + } + + return componentInstance; + } + + + private List getUpdatedRelations(Stream toRelationsInfoStream, + Stream fromRelationsInfoStream) { + Stream updatedRelationsStream = Stream.empty(); + + if (toRelationsInfoStream != null) { + updatedRelationsStream = Stream.concat(updatedRelationsStream, toRelationsInfoStream); + } + + if (fromRelationsInfoStream != null) { + updatedRelationsStream = Stream.concat(updatedRelationsStream, fromRelationsInfoStream); + } + + return updatedRelationsStream.collect(Collectors.toList()); + } + + private List getRelations(Function getNodeFunc, + Component containerComponent, + ComponentInstance currentResourceInstance) { + + final List componentInstancesRelations = containerComponent.getComponentInstancesRelations(); + final String vfInstanceId = currentResourceInstance.getUniqueId(); + + return componentInstancesRelations.stream() + .filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId)) + .collect(Collectors.toList()); + } + + private List convert(List relationsDef, + Function mapFunc) { + return relationsDef.stream() + .map(mapFunc::apply) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private RelationMergeInfo mapRelationCapability(RequirementCapabilityRelDef relDef, List vfcInstances) { + // Id of the VfcInstance that is the owner of the capability + String ownerId = relDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId(); + return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceCapability(currVfcInst, relDef)); + } + + private RelationMergeInfo mapRelationRequirement(RequirementCapabilityRelDef relDef, List vfcInstances) { + // Id of the VfcInstance that is the owner of the requirement + String ownerId = relDef.resolveSingleRelationship().getRelation().getRequirementOwnerId(); + return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relDef)); + } + + private RelationMergeInfo createRelationMergeInfo(List vfcInstances, String ownerId, Function mapFunc) { + return vfcInstances.stream() + .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId)) + .map(mapFunc::apply) + .filter(Objects::nonNull) + .findAny() + .orElse(null); + } + + + private RelationMergeInfo mapVfcInstanceCapability(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) { + String capabilityUniqueId = relDef.resolveSingleRelationship().getRelation().getCapabilityUid(); + + + String vfcInstanceName = vfcInstance.getName(); + String vfcUid = vfcInstance.getComponentUid(); + + Either vfcResource = toscaOperationFacade.getToscaElement(vfcUid); + if(vfcResource.isLeft()) { + Resource vfc = vfcResource.left().value(); + + CapabilityDefinition capabilityDef = retrieveCapabilityDefinition(capabilityUniqueId, vfc); + String capabilityType; + String capabilityName; + if (capabilityDef != null) { + capabilityType = capabilityDef.getType(); + capabilityName = capabilityDef.getName(); + } + else { + log.debug("Failed to retrieve capability type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId); + capabilityType = null; + capabilityName = null; + } + + return new RelationMergeInfo(capabilityType, capabilityName, vfcInstanceName, relDef); + } + else { + log.debug("Failed to load VFC by uid {}", vfcUid); + return null; + } + } + + private RelationMergeInfo mapVfcInstanceRequirement(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) { + String requirementUniqueId = relDef.resolveSingleRelationship().getRelation().getRequirementUid(); + + String vfcInstanceName = vfcInstance.getName(); + String vfcUid = vfcInstance.getComponentUid(); + + Either vfcResource = toscaOperationFacade.getToscaElement(vfcUid); + if(vfcResource.isLeft()) { + Resource vfc = vfcResource.left().value(); + + RequirementDefinition requirementDef = retrieveRequirementDefinition(requirementUniqueId, vfc); + String requirementType; + String requirementName; + if (requirementDef != null) { + requirementType = requirementDef.getCapability(); + requirementName = requirementDef.getName(); + } + else { + log.debug("Failed to retrieve requirement type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId); + requirementType = null; + requirementName = null; + } + + return new RelationMergeInfo(requirementType, requirementName, vfcInstanceName, relDef); + } + else { + log.debug("Failed to load VFC by uid {}", vfcUid); + return null; + } + } + + private CapabilityDefinition retrieveCapabilityDefinition(String uniqueId, Resource vfc) { + return vfc.getCapabilities().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())) + .findFirst() + .orElse(null); + } + + private String retrieveCapabilityUid(String name, Component vfc) { + return vfc.getCapabilities().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> name.equals(def.getName())) + .findFirst() + .map(CapabilityDefinition::getUniqueId) + .orElse(null); + } + + private RequirementDefinition retrieveRequirementDefinition(String uniqueId, Resource vfc) { + return vfc.getRequirements().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> uniqueId.equals(def.getUniqueId())) + .findFirst() + .orElse(null); + } + + private String retrieveRequirementUid(String name, Component vfc) { + return vfc.getRequirements().values().stream() + .flatMap(List::stream) + .filter(Objects::nonNull) + .filter(def -> name.equals(def.getName())) + .findFirst() + .map(RequirementDefinition::getUniqueId) + .orElse(null); + } + + + + private VfRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder, + Component updatedContainerComponent, + Wrapper> resultWrapper) { + VfRelationsMergeInfo vfRelationsMergeInfo = dataHolder.getVfRelationsMergeInfo(); + if (vfRelationsMergeInfo == null) { + log.debug("There is no info about relations should be restored."); + resultWrapper.setInnerElement(Either.left(updatedContainerComponent)); + } + + return vfRelationsMergeInfo; + } + + + private RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo, + String newInstanceId, + Map vfciMap, + Component updatedContainerComponent) { + String oldVfcInstanceName = oldCapInfo.getVfcInstanceName(); + + ComponentInstance newVfcInstance = vfciMap.get(oldVfcInstanceName); + if (newVfcInstance != null) { + // Append relation to updated container + RequirementCapabilityRelDef oldRelDef = oldCapInfo.getRelDef(); + oldRelDef.setToNode(newInstanceId); + + RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation(); + oldRelationshipInfo.setCapabilityOwnerId(newVfcInstance.getUniqueId()); + oldRelationshipInfo.getRelationship().setType(oldCapInfo.getCapReqType()); + + + String vfcUid = newVfcInstance.getComponentUid(); + Either eitherComponent = toscaOperationFacade.getToscaElement(vfcUid); + + if(eitherComponent.isLeft()) { + String capabilityUid = retrieveCapabilityUid(oldCapInfo.getCapReqName() , eitherComponent.left().value()); + oldRelationshipInfo.setCapabilityUid(capabilityUid); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid); + } + + updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef); + return oldRelDef; + } + else { + log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName); + return null; + } + } + + + + private RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo, + String newInstanceId, + Map vfciMap, + Component updatedContainerComponent) { + String oldVfcInstanceName = oldReqInfo.getVfcInstanceName(); + + ComponentInstance newVfcInstance = vfciMap.get(oldReqInfo.getVfcInstanceName()); + if (newVfcInstance != null) { + // Append relation to updated container + RequirementCapabilityRelDef oldRelDef = oldReqInfo.getRelDef(); + oldRelDef.setFromNode(newInstanceId); + + RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation(); + oldRelationshipInfo.setRequirementOwnerId(newVfcInstance.getUniqueId()); + oldRelationshipInfo.getRelationship().setType(oldReqInfo.getCapReqType()); + + String vfcUid = newVfcInstance.getComponentUid(); + Either eitherComponent = toscaOperationFacade.getToscaElement(vfcUid); + + if(eitherComponent.isLeft()) { + String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName() , eitherComponent.left().value()); + oldRelationshipInfo.setRequirementUid(requirementUid); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid); + } + + updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef); + return oldRelDef; + } + else { + log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName); + return null; + } + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java new file mode 100644 index 0000000000..5dcb1dda79 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; + +public interface ComponentsMergeCommand { + + /** + * encapsulates the logic of merging component inner entities from the previous component into the currently updated component + * @param prevComponent the old component, whose entities need to be merged + * @param currentComponent the new component, whose entities need to be merged + * @return the status of the merge process + */ + ActionStatus mergeComponents(Component prevComponent, Component currentComponent); + + /** + * + * @return short description of the command for logging purposes + */ + String description(); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java index c5fb1d4a86..ac0959897d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java @@ -6,8 +6,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; @@ -23,6 +24,10 @@ public class DataForMergeHolder { private Map origCompInstDeploymentArtifactsCreatedOnTheInstance; private Map origCompInstInformationalArtifactsCreatedOnTheInstance; private List origComponentInstanceHeatEnvArtifacts; + private VfRelationsMergeInfo vfRelationsMergeInfo; + private List origInstanceCapabilities; + private Component origInstanceNode; + private String origComponentInstId; public DataForMergeHolder() { origComponentInstanceInputs = new ArrayList<>(); @@ -30,7 +35,7 @@ public class DataForMergeHolder { origComponentInputs = new ArrayList<>(); origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>(); - + origInstanceCapabilities = new ArrayList<>(); } public List getOrigComponentInstanceHeatEnvArtifacts() { @@ -109,6 +114,35 @@ public class DataForMergeHolder { origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts; } + public void setVfRelationsInfo(VfRelationsMergeInfo vfRelationsMergeInfo) { + this.vfRelationsMergeInfo = vfRelationsMergeInfo; + } + + public VfRelationsMergeInfo getVfRelationsMergeInfo() { + return vfRelationsMergeInfo; + } + + public List getOrigInstanceCapabilities() { + return origInstanceCapabilities; + } + public void setOrigInstanceCapabilities(List origInstanceCapabilities) { + this.origInstanceCapabilities = origInstanceCapabilities; + } + public Component getOrigInstanceNode() { + return origInstanceNode; + } + + public void setOrigInstanceNode(Component origInstanceNode) { + this.origInstanceNode = origInstanceNode; + } + + public String getOrigComponentInstId() { + return origComponentInstId; + } + + public void setOrigComponentInstId(String origComponentInstId) { + this.origComponentInstId = origComponentInstId; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java new file mode 100644 index 0000000000..4ab802ad35 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java @@ -0,0 +1,49 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; + +public class RelationMergeInfo { + private String capReqType; + private String vfcInstanceName; + private RequirementCapabilityRelDef relDef; + private String capReqName; + + public RelationMergeInfo(String capReqType, String capReqName, String vfcInstanceName, RequirementCapabilityRelDef relDef) { + this.capReqType = capReqType; + this.capReqName = capReqName; + this.vfcInstanceName = vfcInstanceName; + this.relDef = relDef; + } + + public String getCapReqType() { + return capReqType; + } + + public void setCapReqType(String type) { + this.capReqType = type; + } + + public String getVfcInstanceName() { + return vfcInstanceName; + } + + public void setVfcInstanceName(String vfcInstanceName) { + this.vfcInstanceName = vfcInstanceName; + } + + public RequirementCapabilityRelDef getRelDef() { + return relDef; + } + + public void setRelDef(RequirementCapabilityRelDef relDef) { + this.relDef = relDef; + } + + public String getCapReqName() { + return capReqName; + } + + public void setCapReqName(String capReqName) { + this.capReqName = capReqName; + } +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java new file mode 100644 index 0000000000..e116b66408 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import java.util.List; + +public class VfRelationsMergeInfo { + private List fromRelationsInfo; + private List toRelationsInfo; + + public VfRelationsMergeInfo(List fromRelationsInfo, List toRelationsInfo) { + this.fromRelationsInfo = fromRelationsInfo; + this.toRelationsInfo = toRelationsInfo; + } + + public List getFromRelationsInfo() { + return fromRelationsInfo; + } + + public void setFromRelationsInfo(List fromRelationsInfo) { + this.fromRelationsInfo = fromRelationsInfo; + } + + public List getToRelationsInfo() { + return toRelationsInfo; + } + + public void setToRelationsInfo(List toRelationsInfo) { + this.toRelationsInfo = toRelationsInfo; + } + +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java deleted file mode 100644 index 4e49eef94c..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.openecomp.sdc.be.components.merge.property; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import fj.data.Either; - -@org.springframework.stereotype.Component -public class ComponentInstanceInputsMergeBL { - - @javax.annotation.Resource - private ToscaOperationFacade toscaOperationFacade; - - @javax.annotation.Resource - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - - public ActionStatus mergeComponentInstancesInputs(Component oldComponent, Component newComponent) { - Map> componentInstancesInputs = newComponent.getComponentInstancesInputs(); - if (componentInstancesInputs == null) { - return ActionStatus.OK; - } - componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(oldComponent, newComponent, instanceId, instInputs)); - return updateComponentInstancesInputs(newComponent, componentInstancesInputs); - } - - public ActionStatus mergeComponentInstanceInputs(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { - List newInstInput = newComponent.safeGetComponentInstanceInput(instanceId); - if (newInstInput == null) { - return ActionStatus.OK; - } - propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstInput, newComponent.getInputs()); - return updateComponentInstanceInputs(newComponent, instanceId, newInstInput); - } - - private ActionStatus updateComponentInstanceInputs(Component newComponent, String instanceId, List newInstInput) { - StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceInputs(newComponent, instanceId, newInstInput); - if (storageOperationStatus != StorageOperationStatus.OK) { - return componentsUtils.convertFromStorageResponse(storageOperationStatus); - } - return ActionStatus.OK; - } - - private ActionStatus updateComponentInstancesInputs(Component component, Map> componentInstancesInputs) { - Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId()); - if (mapStorageOperationStatusEither.isRight()) { - return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); - } - return ActionStatus.OK; - } - - private void mergeOldInstanceInputsValues(Component oldComponent, Component newComponent, String instanceId, List instInputs) { - ComponentInstance currentCompInstance = newComponent.getComponentInstanceById(instanceId).get(); - List oldInstInputs = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceInputsByName(currentCompInstance.getName()); - List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); - propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs()); - } - - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java deleted file mode 100644 index 43e3ec624a..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openecomp.sdc.be.components.merge.property; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -import fj.data.Either; - -@org.springframework.stereotype.Component -public class ComponentInstancePropertiesMergeBL { - - @javax.annotation.Resource - private ToscaOperationFacade toscaOperationFacade; - - @javax.annotation.Resource(name = "componentUtils") - private ComponentsUtils componentsUtils; - - @javax.annotation.Resource - private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic; - - public ActionStatus mergeComponentInstancesProperties(Component oldComponent, Resource newResource) { - Map> newInstProps = newResource.getComponentInstancesProperties(); - if (newInstProps == null) { - return ActionStatus.OK; - } - newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(oldComponent, newResource, instanceId, newProps) ); - return updateComponentInstancesProperties(newResource, newInstProps); - } - - - public ActionStatus mergeComponentInstanceProperties(List oldInstProps, List oldInputs, Component newComponent, String instanceId) { - List newInstProps = newComponent.safeGetComponentInstanceProperties(instanceId); - if (newInstProps == null) { - return ActionStatus.OK; - } - propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstProps, newComponent.getInputs()); - return updateComponentInstanceProperties(newComponent, instanceId, newInstProps); - } - - private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId, List newProps) { - List oldInstProperties = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId); - List oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs(); - propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProperties, oldInputs, newProps, newComponent.getInputs()); - } - - private ActionStatus updateComponentInstancesProperties(Component newComponent, Map> newInstProps) { - Either>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId()); - if (mapStorageOperationStatusEither.isRight()) { - return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value()); - } - return ActionStatus.OK; - } - - private ActionStatus updateComponentInstanceProperties(Component component, String instanceId, List newInstProps) { - StorageOperationStatus storageOperationStatus = toscaOperationFacade.updateComponentInstanceProperties(component, instanceId, newInstProps); - if (storageOperationStatus != StorageOperationStatus.OK) { - return componentsUtils.convertFromStorageResponse(storageOperationStatus); - } - return ActionStatus.OK; - } - - - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java index 96d3bce97e..139ac386a1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java @@ -1,11 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.List; - import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.springframework.stereotype.Component; +import java.util.Collections; +import java.util.List; + @Component public class DataDefinitionsValuesMergingBusinessLogic { @@ -30,6 +31,11 @@ public class DataDefinitionsValuesMergingBusinessLogic { } + public void mergeInstanceDataDefinitions(List oldInstanceDataDefinition, List updatedInstanceDataDefinition) { + List emptyInputsList = Collections.emptyList(); + mergeInstanceDataDefinitions(oldInstanceDataDefinition, emptyInputsList, updatedInstanceDataDefinition, emptyInputsList); + } + private void mergeInstanceDefinition(MergePropertyData mergeData) { if (isSameType(mergeData.getOldProp(), mergeData.getNewProp())) { propertyValueMergeBL.mergePropertyValue(mergeData.getOldProp(), mergeData.getNewProp(), mergeData.getGetInputNamesToMerge()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java index 63a7a1b3a0..df65c1161f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.components.merge.property; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + import java.util.ArrayList; import java.util.List; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - /** * A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link org.openecomp.sdc.be.model.ComponentInstanceInput}) * that its value needs to be merged during an upgrade of a VSP. diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java index 6b083596c7..318840d60a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java @@ -1,15 +1,7 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - -import org.openecomp.sdc.be.components.impl.ImportUtils; +import com.google.gson.Gson; +import fj.data.Either; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -22,9 +14,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.gson.Gson; - -import fj.data.Either; +import javax.annotation.Resource; +import java.util.*; +import java.util.stream.Collectors; @Component public class PropertyDataValueMergeBusinessLogic { @@ -88,39 +80,6 @@ public class PropertyDataValueMergeBusinessLogic { return propertyConvertor.convertToToscaObject(propertyType, propValue, innerType, dataTypes); } - - @SuppressWarnings("unchecked") - private Object removeUnwantedGetInputValues(Object val, List getInputNamesToMerge) { - if (val instanceof Map) { - return removeUnwantedGetInputValues((Map) val, getInputNamesToMerge); - } - if (val instanceof List) { - return removeUnwantedGetInputValues((List)val, getInputNamesToMerge); - } - return val; - } - - private List removeUnwantedGetInputValues(List listVal, List getInputNamesToMerge) { - return listVal.stream().map(val -> removeUnwantedGetInputValues(val, getInputNamesToMerge)).collect(Collectors.toList()); - } - - private Map removeUnwantedGetInputValues(Map val, List getInputNamesToMerge) { - return val.entrySet().stream().filter(entry -> !isGetInputEntry(entry) || isGetInputToMerge(getInputNamesToMerge, entry)) - .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), getInputNamesToMerge))); - } - - private boolean isGetInputToMerge(List getInputNamesToMerge, Map.Entry entry) { - return getInputNamesToMerge.contains(retrieveGetInputInputName(entry.getValue())); - } - - private String retrieveGetInputInputName(Object getInputValue) { - return getInputValue instanceof List ? (String)((List) getInputValue).get(0) : (String)getInputValue; - } - - private boolean isGetInputEntry(Map.Entry oldValEntry) { - return oldValEntry.getKey().equals(ImportUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); - } - private boolean isEmptyValue(Object val) { return val == null || val instanceof Map && ((Map) val).isEmpty() || diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java index 09f26a39ee..df3030567d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java @@ -1,15 +1,15 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + public class PropertyInstanceMergeDataBuilder { private final static PropertyInstanceMergeDataBuilder INSTANCE = new PropertyInstanceMergeDataBuilder(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java index 88601bb521..9fcb864fe9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be.components.merge.property; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.ImportUtils; + import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.apache.commons.lang.StringUtils; -import org.openecomp.sdc.be.components.impl.ImportUtils; - public abstract class PropertyValueMerger { abstract Object merge(Object oldVal, Object newVal, List someStrings); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java index 39381e7322..ce0ed0eed2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java @@ -1,9 +1,9 @@ package org.openecomp.sdc.be.components.merge.property; -import java.util.List; - import org.springframework.stereotype.Component; +import java.util.List; + @Component("scalar-prop-value-merger") public class ScalarPropertyValueMerger extends PropertyValueMerger { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java index 9d11eb9aaf..cdfeded356 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java @@ -1,14 +1,13 @@ package org.openecomp.sdc.be.components.merge.resource; +import fj.data.Either; import org.openecomp.sdc.be.components.merge.GlobalTypesMergeBusinessLogic; import org.openecomp.sdc.be.components.merge.TopologyComparator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import org.springframework.stereotype.Component; -import fj.data.Either; - @Component public class MergeResourceBLFactory { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java index 251fb1a64e..0ffe693187 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java @@ -1,62 +1,38 @@ package org.openecomp.sdc.be.components.merge.resource; -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic { - private final static Logger log = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class); - @javax.annotation.Resource - private ComponentInputsMergeBL inputsValuesMergeBL; + private List componentMergingCommands; - @javax.annotation.Resource - private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBL; - - @javax.annotation.Resource - private ComponentInstanceInputsMergeBL instanceInputsValueMergeBL; + public ResourceDataMergeBusinessLogic(List componentMergingCommands) { + this.componentMergingCommands = componentMergingCommands; + } @Override public ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) { if (oldResource == null) { return ActionStatus.OK; } - - ActionStatus mergeInstInputsStatus = instancePropertiesValueMergeBL.mergeComponentInstancesProperties(oldResource, newResource); - if (mergeInstInputsStatus != ActionStatus.OK) { - log.error("failed to merge instance properties of resource {} status is {}", newResource.getUniqueId(), mergeInstInputsStatus); - return mergeInstInputsStatus; - } - - ActionStatus mergeInstPropsStatus = instanceInputsValueMergeBL.mergeComponentInstancesInputs(oldResource, newResource); - if (mergeInstPropsStatus != ActionStatus.OK) { - log.error("failed to merge instance inputs of resource {} status is {}", newResource.getUniqueId(), mergeInstPropsStatus); - return mergeInstPropsStatus; - } - - ActionStatus mergeInputsStatus = mergeInputs(oldResource, newResource); - if (mergeInputsStatus != ActionStatus.OK) { - log.error("failed to merge inputs of resource {} status is {}", newResource.getUniqueId(), mergeInputsStatus); - return mergeInputsStatus; + for (ComponentsMergeCommand componentMergeCommand : componentMergingCommands) { + ActionStatus mergeStatus = componentMergeCommand.mergeComponents(oldResource, newResource); + if (mergeStatus != ActionStatus.OK) { + LOGGER.error("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), mergeStatus); + return mergeStatus; + } } return ActionStatus.OK; } - private ActionStatus mergeInputs(Resource oldResource, Resource newResource) { - List inputsToMerge = newResource.getInputs() != null ? newResource.getInputs() : new ArrayList<>(); - return inputsValuesMergeBL.mergeAndRedeclareComponentInputs(oldResource, newResource, inputsToMerge); - } - - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java new file mode 100644 index 0000000000..4ff7e06db5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java @@ -0,0 +1,257 @@ +package org.openecomp.sdc.be.components.merge.utils; + +import fj.data.Either; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.annotations.VisibleForTesting; +import java.util.*; +import java.util.stream.Collectors; + +import static java.util.function.Function.identity; + +/** + * This class is Utils class but it should be bean + * @author dr2032 + * + */ +@org.springframework.stereotype.Component("MergeInstanceUtils") +public class MergeInstanceUtils { + private Logger log = LoggerFactory.getLogger(MergeInstanceUtils.class); + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + /** + * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance + * @param container containing new component instance + * @param origInstanceNode old component (in case of PROXY it should be actual service) + * @param newInstanceId - ID of new instance of the component + * @param oldCapabilitiesOwnerIds + * @return + */ + public Map mapOldToNewCapabilitiesOwnerIds(Component container, + Component origInstanceNode, + String newInstanceId, + List oldCapabilitiesOwnerIds) { + + Map resultMap; + + if (ModelConverter.isAtomicComponent(origInstanceNode) || isCVFC(origInstanceNode)) { + resultMap = prepareMapForAtomicComponent(newInstanceId, oldCapabilitiesOwnerIds); + } + else { + resultMap = prepareMapForNonAtomicComponent(container, origInstanceNode, newInstanceId, oldCapabilitiesOwnerIds); + } + + return resultMap; + } + + + private static boolean isCVFC(Component component) { + ComponentTypeEnum componentType = component.getComponentType(); + if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { + return false; + } + + Resource resource = (Resource) component; + ResourceTypeEnum resourceType = resource.getResourceType(); + return resourceType == ResourceTypeEnum.CVFC; + } + + + /** + * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance + * @param oldInstance + * @param newInstance + * @return + */ + public Map mapOldToNewCapabilitiesOwnerIds(ComponentInstance oldInstance, ComponentInstance newInstance) { + List oldVfcInstances = getVfcInstances(oldInstance); + List newVfcInstances = getVfcInstances(newInstance); + + Map newVfciNameMap = convertToVfciNameMap(newVfcInstances); + + return oldVfcInstances.stream() + .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName())) + .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId())); + } + + + /** + * Method converts list of Component Instances to map of the instances where the key is their name + * @param componentInstances + * @return + */ + public Map convertToVfciNameMap(List componentInstances) { + return componentInstances != null ? + componentInstances.stream() + .collect(Collectors.toMap(ComponentInstance::getName, identity())): Collections.emptyMap(); + } + + + + /** + * Returns List of componentInstances by specified componentInstance + * If componentInstance is for atomic component the returned list will contain the specified componentInstance only. + * @param componentInstance + * @return + */ + public List getVfcInstances(ComponentInstance componentInstance) { + if (componentInstance == null) { + return Collections.emptyList(); + } + + + List vfcInstances; + + String componentId = componentInstance.getActualComponentUid(); + Either eitherComponent = toscaOperationFacade.getToscaElement(componentId); + + if(eitherComponent.isLeft()) { + Component component = eitherComponent.left().value(); + vfcInstances = getVfcInstances(componentInstance, component); + } + else { + log.debug("Unexpected error: resource was not loaded for VF ID: {}", componentId); + vfcInstances = Collections.emptyList(); + } + + return vfcInstances; + } + + + /** + * Returns List of componentInstances by specified componentInstance and component + * If componentInstance is for atomic component the returned list will contain the specified componentInstance only. + * @param componentInstance + * @param eitherComponent + * @return + */ + public List getVfcInstances(ComponentInstance componentInstance, Component component) { + if (componentInstance == null || component == null) { + return Collections.emptyList(); + } + + + List vfcInstances; + + if (ModelConverter.isAtomicComponent(component) || isCVFC(component)) { + if (componentInstance.getIsProxy()) { + // Component is proxy and it doesn't contain required data + vfcInstances = getVfcInstances(componentInstance); + } + else { + vfcInstances = Arrays.asList(componentInstance); + } + } + else { + vfcInstances = recursiveScanForAtomicComponentInstances(component); + } + + return vfcInstances; + } + + + @VisibleForTesting + public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) { + this.toscaOperationFacade = toscaOperationFacade; + } + + + + /** + * @param component + * @return + */ + private List recursiveScanForAtomicComponentInstances(Component component) { + List vfcInstances; + + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + // Go recursively to collect atomic components only + vfcInstances = componentInstances.stream() + .map(this::getVfcInstances) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + else { + vfcInstances = Collections.emptyList(); + } + + return vfcInstances; + } + + + + /** + * @param newInstanceId + * @param oldCapabilitiesOwnerIds + * @return + */ + private Map prepareMapForAtomicComponent(String newInstanceId, List oldCapabilitiesOwnerIds) { + Map resultMap; + + int oldCapabilityOwnerIdsSize = oldCapabilitiesOwnerIds.size(); + if (oldCapabilityOwnerIdsSize == 1) { + resultMap = new HashMap<>(); + resultMap.put(oldCapabilitiesOwnerIds.get(0), newInstanceId); + } + else { + log.debug("For automic component the list of old capabilities owner Ids should contains one element while actual size is {},", oldCapabilityOwnerIdsSize); + resultMap = Collections.emptyMap(); + } + + return resultMap; + } + + /** + * @param container + * @param origInstanceNode + * @param newInstanceId + * @param oldCapabilitiesOwnerIds + * @return + */ + private Map prepareMapForNonAtomicComponent(Component container, Component origInstanceNode, + String newInstanceId, List oldCapabilitiesOwnerIds) { + Map resultMap; + List oldVfcInstances = recursiveScanForAtomicComponentInstances(origInstanceNode); + + ComponentInstance newInstance = container.getComponentInstanceById(newInstanceId).orElse(null); + if (newInstance == null) { + log.debug("Failed to get component instance by newInstanceId: {}.", newInstanceId); + resultMap = Collections.emptyMap(); + } + else { + resultMap = mapOldVfcIdsToNewOnes(oldCapabilitiesOwnerIds, oldVfcInstances, newInstance); + } + return resultMap; + } + + /** + * @param oldCapabilitiesOwnerIds + * @param oldVfcInstances + * @param newInstance + * @return + */ + private Map mapOldVfcIdsToNewOnes(List oldCapabilitiesOwnerIds, + List oldVfcInstances, ComponentInstance newInstance) { + List newVfcInstances = getVfcInstances(newInstance); + Map newVfciNameMap = convertToVfciNameMap(newVfcInstances); + + return oldVfcInstances.stream() + .filter(oldVfc -> oldCapabilitiesOwnerIds.contains(oldVfc.getUniqueId())) + .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName())) + .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId())); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java new file mode 100644 index 0000000000..469ae31f2d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java @@ -0,0 +1,173 @@ +package org.openecomp.sdc.be.components.path; + +import fj.data.Either; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +@Component("forwardingPathValidator") +public class ForwardingPathValidator { + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + private static final Logger LOGGER = LoggerFactory.getLogger(ForwardingPathValidator.class); + private static final int PATH_NAME_LENGTH = 200; + private static final int PROTOCOL_LENGTH = 200; + private static final int DESTINATION_PORT_LENGTH = 200; + + public Either validateForwardingPaths(Collection paths, + String serviceId, boolean isUpdate) { + for (ForwardingPathDataDefinition path : paths) { + Either forwardingPathResponseEither = validateForwardingPath(path, + serviceId, isUpdate); + if (forwardingPathResponseEither.isRight()) { + return forwardingPathResponseEither; + } + } + return Either.left(Boolean.TRUE); + } + + private Either validateForwardingPath(ForwardingPathDataDefinition path, + String serviceId, boolean isUpdate) { + ResponseFormatManager responseFormatManager = getResponseFormatManager(); + + Either errorResponseName = validateName(path, + responseFormatManager, serviceId, isUpdate); + if (errorResponseName != null) + return errorResponseName; + + Either protocolErrorResponse = validateProtocol(path, responseFormatManager); + if (protocolErrorResponse != null) + return protocolErrorResponse; + + Either portNumberResponse = validateDestinationPortNumber(path, responseFormatManager); + if (portNumberResponse != null) + return portNumberResponse; + + return Either.left(true); + } + + private Either validateDestinationPortNumber(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager) { + if (dataDefinition.getDestinationPortNumber() != null && + dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH ) { + LOGGER.debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ", + dataDefinition.getDestinationPortNumber()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, dataDefinition.getDestinationPortNumber()); + return Either.right(errorResponse); + } + return null; + } + + private Either validateProtocol(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager) { + if (dataDefinition.getProtocol() != null && dataDefinition.getProtocol().length() > PROTOCOL_LENGTH) { + LOGGER.debug("Forwarding path protocol {} too long, , maximum allowed 200 characters ", dataDefinition.getProtocol()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH, dataDefinition.getProtocol()); + return Either.right(errorResponse); + } + return null; + } + + private Either validateName(ForwardingPathDataDefinition dataDefinition, + ResponseFormatManager responseFormatManager, + String serviceId, boolean isUpdate) { + String pathName = dataDefinition.getName(); + Either pathEmptyResponse = validatePathNameIfEmpty(responseFormatManager, pathName); + if (pathEmptyResponse != null) + return pathEmptyResponse; + + Either pathLengthResponse = validatePathNameLength(responseFormatManager, pathName); + if (pathLengthResponse != null) + return pathLengthResponse; + + Either isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager ); + if(isPathNameUniqueResponse.isRight()) { + return Either.right(isPathNameUniqueResponse.right().value()); + } + if (!isPathNameUniqueResponse.left().value()) { + LOGGER.debug("Forwarding path name {} already in use ", dataDefinition.getName()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_NAME_ALREADY_IN_USE, dataDefinition.getName()); + return Either.right(errorResponse); + } + return null; + } + + private Either validatePathNameLength(ResponseFormatManager responseFormatManager, String pathName) { + if (pathName.length() > PATH_NAME_LENGTH) { + LOGGER.debug("Forwarding path name {} too long, , maximum allowed 200 characters ", pathName); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus + .FORWARDING_PATH_NAME_MAXIMUM_LENGTH, pathName); + return Either.right(errorResponse); + } + return null; + } + + private Either validatePathNameIfEmpty(ResponseFormatManager responseFormatManager, String pathName) { + if (StringUtils.isEmpty(pathName)) { + LOGGER.debug("Forwarding Path Name can't be empty"); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.FORWARDING_PATH_NAME_EMPTY); + return Either.right(errorResponse); + } + return null; + } + + + private Either validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId, + boolean isUpdate, ResponseFormatManager responseFormatManager) { + boolean isPathNameUnique = false; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreForwardingPath(false); + Either forwardingPathOrigin = toscaOperationFacade + .getToscaElement(serviceId, filter); + if (forwardingPathOrigin.isRight()){ + return Either.right(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + Collection allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values(); + Map pathNames = new HashMap<>(); + allPaths.forEach( path -> pathNames.put(path.getUniqueId(), path.getName()) ); + + if (isUpdate){ + for(Map.Entry entry : pathNames.entrySet()){ + if (entry.getKey().equals(dataDefinition.getUniqueId()) && entry.getValue(). + equals(dataDefinition.getName())) { + isPathNameUnique = true; + } + + if(entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())){ + isPathNameUnique = true; + } + } + } + else + if (!pathNames.values().contains(dataDefinition.getName())){ + isPathNameUnique = true; + } + + return Either.left(isPathNameUnique); + } + + protected ResponseFormatManager getResponseFormatManager() { + return ResponseFormatManager.getInstance(); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java new file mode 100644 index 0000000000..f59831621c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component +public class ComponentInstanceInputPropertyDecelerator extends DefaultPropertyDecelerator { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceInputPropertyDecelerator.class); + private ToscaOperationFacade toscaOperationFacade; + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + public ComponentInstanceInputPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; + } + + @Override + ComponentInstanceInput createDeclaredProperty(PropertyDataDefinition prop) { + return new ComponentInstanceInput(prop); + } + + @Override + Either updatePropertiesValues(Component component, String cmptInstanceId, List properties) { + log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + Map> instProperties = Collections.singletonMap(cmptInstanceId, properties); + return toscaOperationFacade.addComponentInstanceInputsToComponent(component, instProperties); + } + + @Override + Optional resolvePropertiesOwner(Component component, String propertiesOwnerId) { + log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); + return component.getComponentInstanceById(propertiesOwnerId); + } + + @Override + void addPropertiesListToInput(ComponentInstanceInput declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List inputsValueList = input.getInputs(); + if(inputsValueList == null) { + inputsValueList = new ArrayList<>(); // adding the property with the new value for UI + } + inputsValueList.add(declaredProp); + input.setInputs(inputsValueList); + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + List componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId()); + if (CollectionUtils.isEmpty(componentInstanceInputsByInputId)) { + return StorageOperationStatus.OK; + } + componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath())); + return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java new file mode 100644 index 0000000000..ab4c4e29c2 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java @@ -0,0 +1,75 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component +public class ComponentInstancePropertyDecelerator extends DefaultPropertyDecelerator { + + private static final Logger log = LoggerFactory.getLogger(ComponentInstancePropertyDecelerator.class); + private ToscaOperationFacade toscaOperationFacade; + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + public ComponentInstancePropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; + } + + @Override + ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) { + return new ComponentInstanceProperty(prop); + } + + @Override + Either updatePropertiesValues(Component component, String cmptInstanceId, List properties) { + log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId()); + Map> instProperties = Collections.singletonMap(cmptInstanceId, properties); + return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties, cmptInstanceId); + } + + @Override + Optional resolvePropertiesOwner(Component component, String propertiesOwnerId) { + log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); + return component.getComponentInstanceById(propertiesOwnerId); + } + + @Override + void addPropertiesListToInput(ComponentInstanceProperty declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List propertiesList = input.getProperties(); + if(propertiesList == null) { + propertiesList = new ArrayList<>(); // adding the property with the new value for UI + } + propertiesList.add(declaredProp); + input.setProperties(propertiesList); + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + List componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, input.getUniqueId()); + if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) { + return StorageOperationStatus.OK; + } + componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath())); + return toscaOperationFacade.updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), componentInstancePropertiesDeclaredAsInput); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java new file mode 100644 index 0000000000..e053096480 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java @@ -0,0 +1,413 @@ +package org.openecomp.sdc.be.components.property; + +import com.google.gson.Gson; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; + +public abstract class DefaultPropertyDecelerator implements PropertyDecelerator { + + private static final Logger log = LoggerFactory.getLogger(DefaultPropertyDecelerator.class); + private static final short LOOP_PROTECTION_LEVEL = 10; + private final Gson gson = new Gson(); + private ComponentsUtils componentsUtils; + private PropertyOperation propertyOperation; + + public DefaultPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) { + this.componentsUtils = componentsUtils; + this.propertyOperation = propertyOperation; + } + + @Override + public Either, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List propsToDeclare) { + log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + return resolvePropertiesOwner(component, propertiesOwnerId) + .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare)) + .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); + } + + abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop); + + abstract Either updatePropertiesValues(Component component, String propertiesOwnerId, List properties); + + abstract Optional resolvePropertiesOwner(Component component, String propertiesOwnerId); + + abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, PropertyDataDefinition originalProp, InputDefinition input); + + private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) { + log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId); + return StorageOperationStatus.NOT_FOUND; + } + + private Either, StorageOperationStatus> declarePropertiesAsInputs(Component component, PropertiesOwner propertiesOwner, List propsToDeclare) { + PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component.getUniqueId(), propertiesOwner, propsToDeclare); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()) + .left() + .map(updatePropsRes -> inputsProperties.getInputsToCreate()); + } + + private PropertiesDeclarationData createInputsAndOverridePropertiesValues(String componentId, PropertiesOwner propertiesOwner, List propsToDeclare) { + List declaredProperties = new ArrayList<>(); + List createdInputs = propsToDeclare.stream() + .map(propInput -> declarePropertyInput(componentId, propertiesOwner, declaredProperties, propInput)) + .collect(Collectors.toList()); + return new PropertiesDeclarationData(createdInputs, declaredProperties); + } + + private InputDefinition declarePropertyInput(String componentId, PropertiesOwner propertiesOwner, List declaredProperties, ComponentInstancePropInput propInput) { + PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput); + propInput.setOwnerId(null); + propInput.setParentUniqueId(null); + InputDefinition inputDefinition = createInput(componentId, propertiesOwner, propInput, prop); + PROPERTYTYPE declaredProperty = createDeclaredProperty(prop); + if(!declaredProperties.contains(declaredProperty)){ + declaredProperties.add(declaredProperty); + } + addPropertiesListToInput(declaredProperty, prop, inputDefinition); + return inputDefinition; + } + + private InputDefinition createInput(String componentId, PropertiesOwner propertiesOwner, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + String generatedInputName = generateInputName(propertiesOwner.getNormalizedName(), propInput); + return createInputFromProperty(componentId, propertiesOwner, generatedInputName, propInput, prop); + } + + private String generateInputName(String inputName, ComponentInstancePropInput propInput) { + String[] parsedPropNames = propInput.getParsedPropNames(); + if(parsedPropNames != null){ + for(String str: parsedPropNames){ + inputName += "_" + str; + } + } else { + inputName += "_" + propInput.getName(); + } + return inputName; + } + + private PropertyDataDefinition resolveProperty(List propertiesToCreate, ComponentInstancePropInput propInput) { + Optional resolvedProperty = propertiesToCreate.stream() + .filter(p -> p.getName().equals(propInput.getName())) + .findFirst(); + return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput; + } + + private InputDefinition createInputFromProperty(String componentId, PropertiesOwner propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) { + String propertiesName = propInput.getPropertiesName() ; + PropertyDefinition selectedProp = propInput.getInput(); + String[] parsedPropNames = propInput.getParsedPropNames(); + InputDefinition input; + boolean complexProperty = false; + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + complexProperty = true; + input = new InputDefinition(selectedProp); + }else{ + input = new InputDefinition(prop); + } + input.setDefaultValue(prop.getValue()); + input.setName(inputName); + input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName())); + input.setInputPath(propertiesName); + input.setInstanceUniqueId(propertiesOwner.getUniqueId()); + input.setPropertyId(propInput.getUniqueId()); + changePropertyValueToGetInputValue(inputName, parsedPropNames, input, prop, complexProperty); + ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(propertiesOwner.getUniqueId()); + ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(propertiesOwner.getName()); + return input; + } + + private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop, boolean complexProperty) { + JSONObject jobject = new JSONObject(); + if(prop.getValue() == null || prop.getValue().isEmpty()){ + if(complexProperty){ + + jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); + prop.setValue(jobject.toJSONString()); + + }else{ + + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + } + + }else{ + + String value = prop.getValue(); + Object objValue = new Yaml().load(value); + if( objValue instanceof Map || objValue instanceof List){ + if(!complexProperty){ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + + }else{ + Map mappedToscaTemplate = (Map) objValue; + createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); + + String json = gson.toJson(mappedToscaTemplate); + prop.setValue(json); + + } + + }else{ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + } + + } + + + if(CollectionUtils.isEmpty(prop.getGetInputValues())){ + prop.setGetInputValues(new ArrayList<>()); + } + List getInputValues = prop.getGetInputValues(); + + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputId(input.getUniqueId()); + getInputValueDataDefinition.setInputName(input.getName()); + getInputValues.add(getInputValueDataDefinition); + } + + private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ + + while(i >= 1){ + if( i == parsedPropNames.length -1){ + JSONObject jobProp = new JSONObject(); + jobProp.put(GET_INPUT, inputName); + ooj.put(parsedPropNames[i], jobProp); + i--; + return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); + }else{ + JSONObject res = new JSONObject(); + res.put(parsedPropNames[i], ooj); + i --; + res = createJSONValueForProperty (i, parsedPropNames, res, inputName); + return res; + } + } + + return ooj; + } + + private Map createInputValue(Map lhm1, int index, String[] inputNames, String inputName){ + while(index < inputNames.length){ + if(lhm1.containsKey(inputNames[index])){ + Object value = lhm1.get(inputNames[index]); + if (value instanceof Map){ + if(index == inputNames.length -1){ + ((Map) value).put(GET_INPUT, inputName); + return (Map) value; + + }else{ + index++; + return createInputValue((Map)value, index, inputNames, inputName); + } + }else{ + Map jobProp = new HashMap<>(); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + lhm1.put(inputNames[index], jobProp); + return lhm1; + }else{ + lhm1.put(inputNames[index], jobProp); + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + }else{ + Map jobProp = new HashMap<>(); + lhm1.put(inputNames[index], jobProp); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + return jobProp; + }else{ + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + } + return lhm1; + } + + private class PropertiesDeclarationData { + private List inputsToCreate; + private List propertiesToUpdate; + + PropertiesDeclarationData(List inputsToCreate, List propertiesToUpdate) { + this.inputsToCreate = inputsToCreate; + this.propertiesToUpdate = propertiesToUpdate; + } + + List getInputsToCreate() { + return inputsToCreate; + } + + List getPropertiesToUpdate() { + return propertiesToUpdate; + } + } + + Either prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List pathOfComponentInstances) { + Either deleteEither = Either.left(inputForDelete); + String value = inputValue.getValue(); + Map mappedToscaTemplate = (Map) new Yaml().load(value); + + resetInputName(mappedToscaTemplate, inputForDelete.getName()); + + value = ""; + if(!mappedToscaTemplate.isEmpty()){ + Either result = cleanNestedMap(mappedToscaTemplate , true); + Map modifiedMappedToscaTemplate = mappedToscaTemplate; + if (result.isLeft()) + modifiedMappedToscaTemplate = (Map)result.left().value(); + else + log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation + value = gson.toJson(modifiedMappedToscaTemplate); + } + inputValue.setValue(value); + + + List getInputsValues = inputValue.getGetInputValues(); + if(getInputsValues != null && !getInputsValues.isEmpty()){ + Optional op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny(); + if(op.isPresent()){ + getInputsValues.remove(op.get()); + } + } + inputValue.setGetInputValues(getInputsValues); + + Either findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue()); + if (findDefaultValue.isRight()) { + deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())))); + return deleteEither; + + } + String defaultValue = findDefaultValue.left().value(); + inputValue.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + return deleteEither; + } + + private void resetInputName(Map lhm1, String inputName){ + for (Map.Entry entry : lhm1.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { + value = ""; + lhm1.remove(key); + } else if (value instanceof Map) { + Map subMap = (Map)value; + resetInputName(subMap, inputName); + } else { + continue; + } + + } + } + + private Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){ + if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){ + if (deepClone){ + if (!(mappedToscaTemplate instanceof HashMap)) + return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() ); + else + mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone(); + } + return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , LOOP_PROTECTION_LEVEL ) ); + } + else { + log.debug("mappedToscaTemplate is empty "); + return Either.right("mappedToscaTemplate is empty "); + } + } + + /* Mutates the object + * Tail recurse -> traverse the tosca elements and remove nested empty map properties + * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected + * + * @param toscaElement - expected map of tosca values + * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map. + **/ + private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){ + //region - Stop if map is empty + if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map)) + return toscaElement; + //endregion + //region - Remove empty map entries & return null iff empty map + if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) { + Object ret; + Set keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException + for( Object key : ((Map)toscaElement).keySet() ) { + Object value = ((Map) toscaElement).get(key); + ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel ); + if ( ret == null ) + keysToRemove.add(key); + } + Collection set = ((Map) toscaElement).keySet(); + if (CollectionUtils.isNotEmpty(set)) + set.removeAll(keysToRemove); + + if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check + return null; + } + //endregion + else + return null; + return toscaElement; + } + + //@returns true iff map nested maps are all empty + //ignores other collection objects + private boolean isEmptyNestedMap(Object element){ + boolean isEmpty = true; + if (element != null){ + if ( element instanceof Map ){ + if (MapUtils.isEmpty((Map)element)) + isEmpty = true; + else + { + for( Object key : ((Map)(element)).keySet() ){ + Object value = ((Map)(element)).get(key); + isEmpty &= isEmptyNestedMap( value ); + } + } + } else { + isEmpty = false; + } + } + return isEmpty; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java new file mode 100644 index 0000000000..e77287de9f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.be.components.property; + +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; + +public class GetInputUtils { + + private GetInputUtils() { + } + + public static boolean isGetInputValueForInput(GetInputValueDataDefinition inputData, String inputId) { + return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java new file mode 100644 index 0000000000..be3c82fa09 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java @@ -0,0 +1,130 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + +@org.springframework.stereotype.Component +public class PolicyPropertyDecelerator extends DefaultPropertyDecelerator { + + private static final Logger log = LoggerFactory.getLogger(PolicyPropertyDecelerator.class); + private PolicyOperation policyOperation; + + public PolicyPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, PolicyOperation policyOperation) { + super(componentsUtils, propertyOperation); + this.policyOperation = policyOperation; + } + + @Override + PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + return new PropertyDataDefinition(prop); + } + + @Override + Either updatePropertiesValues(Component component, String policyId, List properties) { + log.debug("#updatePropertiesValues - updating policies properties for policy {} on component {}", policyId, component.getUniqueId()); + StorageOperationStatus updateStatus = policyOperation.updatePolicyProperties(component, policyId, properties); + return updateStatus == StorageOperationStatus.OK ? Either.left(updateStatus) : Either.right(updateStatus); + } + + @Override + Optional resolvePropertiesOwner(Component component, String policyId) { + log.debug("#resolvePropertiesOwner - fetching policy {} of component {}", policyId, component.getUniqueId()); + return Optional.ofNullable(component.getPolicyById(policyId)); + } + + @Override + void addPropertiesListToInput(PropertyDataDefinition declaredProp, PropertyDataDefinition originalProp, InputDefinition input) { + List propertiesList = input.getProperties(); + if(propertiesList == null) { + propertiesList = new ArrayList<>(); // adding the property with the new value for UI + } + propertiesList.add(new ComponentInstanceProperty(declaredProp)); + input.setProperties(propertiesList); + + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputForDelete) { + return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId()) + .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)) + .orElse(StorageOperationStatus.OK); + } + + private StorageOperationStatus unDeclarePolicyProperties(Component container, InputDefinition input, PolicyProperties policyProperties) { + String policyId = policyProperties.getPolicyId(); + List propsDeclaredAsInput = policyProperties.getProperties(); + propsDeclaredAsInput.forEach(policyProp -> prepareValueBeforeDelete(input, policyProp, Collections.emptyList())); + return policyOperation.updatePolicyProperties(container, policyId, propsDeclaredAsInput); + } + + private Optional getPolicyPropertiesDeclaredAsInput(Component container, String inputId) { + if (container.getPolicies() == null) { + return Optional.empty(); + } + return container.getPolicies().values() + .stream() + .filter(policy -> Objects.nonNull(policy.getProperties())) + .collect(Collectors.toMap(PolicyDataDefinition::getUniqueId, + p -> getPolicyPropertiesDeclaredAsInput(p, inputId))) + .entrySet() + .stream() + .filter(entry -> !entry.getValue().isEmpty()) + .map(entry -> new PolicyProperties(entry.getKey(), entry.getValue())) + .findFirst(); + } + + private boolean isPropertyDeclaredAsInputByInputId(PropertyDataDefinition property, String inputId) { + if (CollectionUtils.isEmpty(property.getGetInputValues())) { + return false; + } + return property.getGetInputValues().stream() + .filter(Objects::nonNull) + .anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId)); + } + + private List getPolicyPropertiesDeclaredAsInput(PolicyDefinition policy, String inputId) { + return policy.getProperties() + .stream() + .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)) + .collect(Collectors.toList()); + } + + private class PolicyProperties { + private String policyId; + private List properties; + + PolicyProperties(String policyId, List properties) { + this.policyId = policyId; + this.properties = properties; + } + + String getPolicyId() { + return policyId; + } + + public List getProperties() { + return properties; + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java new file mode 100644 index 0000000000..ea311cebb5 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java @@ -0,0 +1,66 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; + +@org.springframework.stereotype.Component +public class PropertyDecelerationOrchestrator { + + private static final Logger log = LoggerFactory.getLogger(PropertyDecelerationOrchestrator.class); + private ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator; + private ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator; + private PolicyPropertyDecelerator policyPropertyDecelerator; + private List propertyDecelerators; + + public PropertyDecelerationOrchestrator(ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator, ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator, PolicyPropertyDecelerator policyPropertyDecelerator) { + this.componentInstanceInputPropertyDecelerator = componentInstanceInputPropertyDecelerator; + this.componentInstancePropertyDecelerator = componentInstancePropertyDecelerator; + this.policyPropertyDecelerator = policyPropertyDecelerator; + propertyDecelerators = Arrays.asList(componentInstanceInputPropertyDecelerator, componentInstancePropertyDecelerator, policyPropertyDecelerator); + } + + public Either, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) { + PropertyDecelerator propertyDecelerator = getPropertyDecelerator(componentInstInputsMap); + Pair> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); + return propertyDecelerator.declarePropertiesAsInputs(component, propsToDeclare.getLeft(), propsToDeclare.getRight()); + } + + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) { + log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId()); + for (PropertyDecelerator propertyDecelerator : propertyDecelerators) { + StorageOperationStatus storageOperationStatus = propertyDecelerator.unDeclarePropertiesAsInputs(component, inputToDelete); + if (StorageOperationStatus.OK != storageOperationStatus) { + log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); + return storageOperationStatus; + } + } + return StorageOperationStatus.OK; + + } + + private PropertyDecelerator getPropertyDecelerator(ComponentInstInputsMap componentInstInputsMap) { + if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceInputsMap())) { + return componentInstanceInputPropertyDecelerator; + } + if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceProperties())) { + return componentInstancePropertyDecelerator; + } + if (!MapUtils.isEmpty(componentInstInputsMap.getPolicyProperties())) { + return policyPropertyDecelerator; + } + throw new IllegalStateException("there are no properties selected for deceleration"); + + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java new file mode 100644 index 0000000000..9255763f2c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; + +public interface PropertyDecelerator { + + /** + * creates a list of inputs from the given list of properties and updates the properties accordingly + * @param component the container + * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc) + * @param propsToDeclare the list of properties that are being declared as inputs + * @return the list of inputs that were created from the given properties + */ + Either, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List propsToDeclare); + + /** + * returns the values of declared properties to each original state before it was declared as an input. + * this function is to be called when an input, that was created by declaring a property, is deleted. + * @param component the container of the input to be deleted + * @param input the input to be deleted + */ + StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java new file mode 100644 index 0000000000..df6cb3f6b9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.components.scheduledtasks; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +public abstract class AbstractScheduleTaskRunner { + private static final Logger log = LoggerFactory.getLogger(AbstractScheduleTaskRunner.class); + public abstract ExecutorService getExecutorService(); + + protected void shutdownExecutor() { + ExecutorService executorService = getExecutorService(); + if (executorService == null) + return; + + executorService.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { + executorService.shutdownNow(); // Cancel currently executing + // tasks + // Wait a while for tasks to respond to being cancelled + if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) + log.debug("Pool did not terminate"); + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + executorService.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java new file mode 100644 index 0000000000..a2659f4559 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.scheduledtasks; + +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.CleanComponentsConfiguration; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +@Component("asdcComponentsCleaner") +public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implements Runnable { + + private static final Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class); + + @javax.annotation.Resource + private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null; + + private List componentsToClean; + private long cleaningIntervalInMinutes; + + private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1, + new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build()); + ScheduledFuture scheduledFuture = null; + + @PostConstruct + public void init() { + log.info("Enter init method of AsdcComponentsCleaner"); + Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); + CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration(); + + if (cleanComponentsConfiguration == null) { + log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration"); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", + "fecth configuration"); + return; + + } + componentsToClean = new ArrayList(); + List components = cleanComponentsConfiguration.getComponentsToClean(); + if (components == null) { + log.info("no component were configured for cleaning"); + } + for (String component : components) { + NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component); + if (typeEnum != null) + componentsToClean.add(typeEnum); + } + + long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes(); + + if (intervalInMinutes < 1) { + log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default"); + intervalInMinutes = 60; + } + cleaningIntervalInMinutes = intervalInMinutes; + + startTask(); + + log.info("End init method of AsdcComponentsCleaner"); + } + + @PreDestroy + public void destroy() { + this.stopTask(); + shutdownExecutor(); + } + + public void startTask() { + + log.debug("start task for cleaning components"); + + try { + + if (scheduledService != null) { + log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes); + scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, + TimeUnit.MINUTES); + + } + } catch (Exception e) { + log.debug("unexpected error occured", e); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", + e.getMessage()); + + } + } + + private void stopTask() { + if (scheduledFuture != null) { + boolean cancelTaskSuccessfully = scheduledFuture.cancel(true); + log.debug("Stop cleaning task. result = {}", cancelTaskSuccessfully); + if (!cancelTaskSuccessfully) { + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", + "try to stop the polling task"); + } + scheduledFuture = null; + } + + } + + @Override + public void run() { + try { + componentsCleanBusinessLogic.cleanComponents(componentsToClean); + } catch (Exception e) { + log.error("unexpected error occured", e); + BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", + e.getMessage()); + } + + } + + @Override + public ExecutorService getExecutorService() { + return scheduledService; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java new file mode 100644 index 0000000000..a09a78165e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.scheduledtasks; + +import fj.data.Either; +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("componentsCleanBusinessLogic") +public class ComponentsCleanBusinessLogic extends BaseBusinessLogic { + + @Autowired + private ResourceBusinessLogic resourceBusinessLogic; + + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; + + private static final Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class); + + public Map, ResponseFormat>> cleanComponents(List componentsToClean) { + + Map, ResponseFormat>> cleanedComponents = new HashMap, ResponseFormat>>(); + + log.trace("start cleanComponents"); + for (NodeTypeEnum type : componentsToClean) { + switch (type) { + case Resource: + processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic); + break; + case Service: + processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic); + break; + default: + log.debug("{} component type does not have cleaning method defined", type); + break; + } + } + + log.trace("end cleanComponents"); + return cleanedComponents; + } + + private void processDeletionForType(Map, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) { + Either, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents(); + if (deleteMarkedResources.isRight()) { + log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage()); + } else { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": "); + for (String id : deleteMarkedResources.left().value()) { + sb.append(id).append(", "); + } + log.debug(sb.toString()); + } + } + cleanedComponents.put(type, deleteMarkedResources); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java new file mode 100644 index 0000000000..eac4ecf813 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.scheduledtasks; + +import com.google.common.annotations.VisibleForTesting; +import fj.data.Either; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction; + +@Component("recoveryThreadManager") +public class RecoveryThreadManager extends AbstractScheduleTaskRunner { + + private static final Logger log = LoggerFactory.getLogger(RecoveryThreadManager.class); + @VisibleForTesting + FixEnvironmentTask task = new FixEnvironmentTask(); + + @Resource + private OperationalEnvironmentDao operationalEnvironmentDao; + + @Autowired + private EnvironmentsEngine environmentsEngine; + + private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(NumberUtils.INTEGER_ONE, + new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build()); + @VisibleForTesting + Integer allowedTimeBeforeStaleSec; + + @PostConstruct + public void init() { + log.debug("Enter init method of RecoveryThreadManager"); + final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager + .getConfigurationManager().getDistributionEngineConfiguration(); + Integer opEnvRecoveryIntervalSec = distributionEngineConfiguration.getOpEnvRecoveryIntervalSec(); + scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec, + TimeUnit.SECONDS); + this.allowedTimeBeforeStaleSec = distributionEngineConfiguration.getAllowedTimeBeforeStaleSec(); + log.debug("End init method of AsdcComponentsCleaner"); + } + + @PreDestroy + public void destroy() { + shutdownExecutor(); + } + + protected class FixEnvironmentTask implements Runnable { + @Override + public void run() { + try { + // Failed Envs + Either, CassandraOperationStatus> eitherFailedEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED); + eitherFailedEnv.bimap(convertToFunction(this::handleFailedeEnvironmentsRecords), convertToFunction( + cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.FAILED, cassandraError))); + + // In-Progress Envs + Either, CassandraOperationStatus> eitherInProgressEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS); + eitherInProgressEnv.bimap(convertToFunction(this::handleInProgressEnvironmentsRecords), + convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS, + cassandraError))); + + // Envs To Connect to UEB topics + Either, CassandraOperationStatus> eitherCompleteEnv = operationalEnvironmentDao + .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED); + eitherCompleteEnv.bimap(convertToFunction(this::handleCompleteEnvironmentsRecords), convertToFunction( + cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.COMPLETED, cassandraError))); + + } catch (Exception e) { + log.debug("error while handling operational environments to be fixed :{}", e.getMessage(), e); + } + } + + private void handleCompleteEnvironmentsRecords(List completeEnvironmentsRecords) { + if (!isEmpty(completeEnvironmentsRecords)) { + completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env)) + .forEach(opEnvEntry -> { + environmentsEngine.createUebTopicsForEnvironment(opEnvEntry); + environmentsEngine.addToMap(opEnvEntry); + }); + } + + } + + private void handleFailedeEnvironmentsRecords(List failedEnvironmentsRecords) { + if (!isEmpty(failedEnvironmentsRecords)) { + failedEnvironmentsRecords.parallelStream() + .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env)); + } + + } + + private void handleInProgressEnvironmentsRecords(List inProgressEnvList) { + if (!isEmpty(inProgressEnvList)) { + + long currentTimeMillis = System.currentTimeMillis(); + if (!isEmpty(inProgressEnvList)) { + List staleInProgressEnvList = inProgressEnvList.stream() + .filter(record -> (record.getLastModified().getTime() + (allowedTimeBeforeStaleSec * 1000)) < currentTimeMillis) + .collect(Collectors.toList()); + staleInProgressEnvList.parallelStream() + .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env)); + } + + } + + } + + private void logFailedRetrieveRecord(EnvironmentStatusEnum recordStatus, CassandraOperationStatus error) { + log.debug("error: {} while retrieving operational environments with status: {}", error, recordStatus); + } + + + } + + @Override + public ExecutorService getExecutorService() { + return scheduledService; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java new file mode 100644 index 0000000000..83f5a5de95 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.be.components.utils; + +import org.apache.tinkerpop.shaded.minlog.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.validation.constraints.NotNull; +import java.security.SecureRandom; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Utils { + + private static final Logger log = LoggerFactory.getLogger(Utils.class); + private static final Pattern COUNTER_PATTERN = Pattern.compile("\\d+$"); + private static final SecureRandom random = new SecureRandom(); + + + private Utils() {} + + public static int getNextCounter(@NotNull List existingValues) { + if (existingValues.isEmpty()) { + return 0; + } + int maxCurrentCounter = 0; + try { + maxCurrentCounter = existingValues.stream() + .map(COUNTER_PATTERN::matcher) + .filter(Matcher::find) + .map(matcher -> matcher.group(0)) + .mapToInt(Integer::parseInt) + .max() + .orElse(0); + } + catch (Exception e) { + Log.warn("Failed in retrieivng counter from existing value: ", e); + maxCurrentCounter = random.nextInt(100) + 50; + } + return ++maxCurrentCounter; + } +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java new file mode 100644 index 0000000000..da098acb13 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java @@ -0,0 +1,34 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +@org.springframework.stereotype.Component +public class AccessValidations { + + private final UserValidations userValidations; + private final ComponentValidations componentValidations; + + + public AccessValidations(UserValidations userValidations, ComponentValidations componentValidations) { + this.userValidations = userValidations; + this.componentValidations = componentValidations; + } + + public Component validateUserCanWorkOnComponentAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId, String actionContext) { + userValidations.validateUserExists(userId, actionContext, false) + .left() + .on(this::onUserError); + + return componentValidations.validateComponentIsCheckedOutByUserAndLockIt(componentTypeEnum, componentId, userId); + } + + private User onUserError(ResponseFormat responseFormat) { + throw new ComponentException(responseFormat); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java new file mode 100644 index 0000000000..c626e29f21 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.validation; + +/** + * Created by chaya on 11/14/2017. + */ +public enum ApiResourceEnum { + + ENVIRONMENT_ID("Environment ID"), + RESOURCE_ID("Resource ID"), + SERVICE_ID("Service ID"); + + private String value; + + ApiResourceEnum(String value) { + this.value = value; + } + + public String getValue() { + return this.value; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java index 15fff52ab9..002ae50cde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java @@ -20,19 +20,126 @@ package org.openecomp.sdc.be.components.validation; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; +import java.util.Set; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; +import org.openecomp.sdc.common.util.ValidationUtils; -public class ComponentValidations { +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static java.util.stream.Collectors.toList; + + +@org.springframework.stereotype.Component +public final class ComponentValidations { + + private final ToscaOperationFacade toscaOperationFacade; + private final IGraphLockOperation graphLockOperation; + + public ComponentValidations(ToscaOperationFacade toscaOperationFacade, IGraphLockOperation graphLockOperation) { + this.toscaOperationFacade = toscaOperationFacade; + this.graphLockOperation = graphLockOperation; + } public static boolean validateComponentInstanceExist(Component component, String instanceId) { return Optional.ofNullable(component.getComponentInstances()) - .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(Collectors.toList())) + .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList())) .filter(instancesIds -> instancesIds.contains(instanceId)) .isPresent(); } + public static String getNormalizedName(ToscaDataDefinition toscaDataDefinition) { + String name = (String) toscaDataDefinition.getToscaPresentationValue(JsonPresentationFields.NAME); + return org.openecomp.sdc.common.util.ValidationUtils.normalizeComponentInstanceName(name); + } + + /** + * The following logic is applied: + * For each name new or existing name we look at the normalized name which is used in Tosca representation + * @param currentName + * @param newName + * @param component + * @return True is new name can be used in this component, false otherwise + */ + public static boolean validateNameIsUniqueInComponent(String currentName, String newName, Component component) { + String normalizedCurrentName = ValidationUtils.normalizeComponentInstanceName(currentName); + String normalizedNewName = ValidationUtils.normalizeComponentInstanceName(newName); + + if (normalizedCurrentName.equals(normalizedNewName)) { + return true; //As it's same entity, still considered unique + } + List groups = component.getGroups(); + List componentInstances = component.getComponentInstances(); + Set existingNames = new HashSet<>(); + if (CollectionUtils.isNotEmpty(groups)) { + List existingGroupNames = groups + .stream() + .map(ComponentValidations::getNormalizedName) + .collect(toList()); + existingNames.addAll(existingGroupNames); + } + if (CollectionUtils.isNotEmpty(componentInstances)) { + List existingInstanceNames = componentInstances + .stream() + .map(ComponentValidations::getNormalizedName) + .collect(toList()); + existingNames.addAll(existingInstanceNames); + } + return !existingNames.contains(normalizedNewName); + } + + public Component validateComponentIsCheckedOutByUserAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId) { + Component component = getComponent(componentId, componentTypeEnum); + + if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { + throw new ComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getName()); + } + + lockComponent(component); + + return component; + } + + private Component getComponent(String componentId, ComponentTypeEnum componentType) { + Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()) + .left() + .on(this::onToscaOperationError); + + if (componentType!=component.getComponentType()) { + throw new ComponentException(ActionStatus.INVALID_RESOURCE_TYPE); + } + + return component; + } + + private void lockComponent(Component component) { + StorageOperationStatus lockComponentStatus = graphLockOperation.lockComponent(component.getUniqueId(), + component.getComponentType().getNodeType()); + if (!StorageOperationStatus.OK.equals(lockComponentStatus)) { + throw new StorageException(lockComponentStatus); + } + } + + private Component onToscaOperationError(StorageOperationStatus storageOperationStatus) { + throw new StorageException(storageOperationStatus); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java new file mode 100644 index 0000000000..c1934ae1c4 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java @@ -0,0 +1,216 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Provides specific functionality for policy + */ +public class PolicyUtils { + + private static final Logger log = LoggerFactory.getLogger(PolicyUtils.class); + + private PolicyUtils() { + // No instances allowed + } + + /** + * Calculates the next integer counter according to the found max counter existing in the provided policies map + * + * @param policies the map of the policies + * @return the integer counter + */ + public static int getNextPolicyCounter(Map policies) { + int nextCounter = 0; + if (MapUtils.isNotEmpty(policies)) { + int nextCounterFromIds = policies.values() + .stream() + .map(p -> extractNextPolicyCounterFromUniqueId(p.getUniqueId())) + .max(Integer::compareTo) + .orElse(0); + int nextCounterFromNames = policies.values() + .stream() + .map(p -> extractNextPolicyCounterFromName(p.getName())) + .max(Integer::compareTo) + .orElse(0); + nextCounter = nextCounterFromIds > nextCounterFromNames ? nextCounterFromIds : nextCounterFromNames; + } + return nextCounter; + } + + /** + * Validates policy fields on policy update. Updates mutable fields + * + * @param recievedPolicy the policy parsed from the HTTP request + * @param validPolicy the copy of the existing policy found on the component + * @param policies all the polices related to the component + * @return validated and updated policy or an error as action status + */ + public static Either validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map policies) { + validateImmutablePolicyFields(recievedPolicy, validPolicy); + return validateUpdateMutablePolicyFields(recievedPolicy, validPolicy, policies); + } + + /** + * Retrieves the set of the excluded policy types for the specified component + * + * @param the component + * @return the set of the policies + */ + public static Set getExcludedPolicyTypesByComponent(Component component) { + if (MapUtils.isEmpty(ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping())) { + return Collections.emptySet(); + } + if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + return ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping() + .get(component.getComponentType().name()); + } + return ConfigurationManager.getConfigurationManager() + .getConfiguration() + .getExcludedPolicyTypesMapping() + .get(((Resource) component).getResourceType().getValue()); + } + + private static int extractNextPolicyCounterFromUniqueId(String uniqueId) { + int counter = 0; + if (StringUtils.isNotEmpty(uniqueId)) { + counter = extractNextPolicyCounter(uniqueId, uniqueId.lastIndexOf(Constants.POLICY_UID_POSTFIX)); + } + return counter; + } + + private static int extractNextPolicyCounterFromName(String policyName) { + int counter = 0; + if (StringUtils.isNotEmpty(policyName)) { + counter = extractNextPolicyCounter(policyName, policyName.length()); + } + return counter; + } + + private static int extractNextPolicyCounter(String policyName, int endIndex) { + int counter = 0; + try { + counter = Integer.valueOf(policyName.substring(policyName.lastIndexOf(Constants.GROUP_POLICY_NAME_DELIMETER) + Constants.GROUP_POLICY_NAME_DELIMETER + .length(), endIndex)) + 1; + } + catch (NumberFormatException | IndexOutOfBoundsException e) { + log.error("The exception {} occurred upon extraction counter from the srting value {}. ", e, policyName); + } + return counter; + } + + private static Either validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map policies) { + return validateUpdatePolicyName(recievedPolicy, validPolicy, policies); + } + + private static void validateImmutablePolicyFields(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy) { + boolean isUpdatedField = isUpdatedField(receivedPolicy.getUniqueId(), validPolicy.getUniqueId()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getUniqueId(), validPolicy.getUniqueId(), JsonPresentationFields.UNIQUE_ID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getComponentName(), validPolicy.getComponentName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getComponentName(), validPolicy.getComponentName(), JsonPresentationFields.CI_COMPONENT_NAME); + } + isUpdatedField = isUpdatedField(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom(), JsonPresentationFields.DERIVED_FROM); + } + isUpdatedField = isUpdatedField(receivedPolicy.getDescription(), validPolicy.getDescription()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getDescription(), validPolicy.getDescription(), JsonPresentationFields.DESCRIPTION); + } + isUpdatedField = isUpdatedField(receivedPolicy.getInvariantName(), validPolicy.getInvariantName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getInvariantName(), validPolicy.getInvariantName(), JsonPresentationFields.CI_INVARIANT_NAME); + } + isUpdatedField = isUpdatedField(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID(), JsonPresentationFields.INVARIANT_UUID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName(), JsonPresentationFields.TYPE); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid(), JsonPresentationFields.TYPE_UNIQUE_ID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID(), JsonPresentationFields.UUID); + } + isUpdatedField = isUpdatedField(receivedPolicy.getVersion(), validPolicy.getVersion()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getVersion(), validPolicy.getVersion(), JsonPresentationFields.VERSION); + } + isUpdatedField = isUpdatedField(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar() + .toString()); + if (isUpdatedField) { + logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar() + .toString(), JsonPresentationFields.IS_FROM_CSAR); + } + } + + private static boolean isUpdatedField(String oldField, String newField) { + boolean isUpdatedField = false; + if (StringUtils.isEmpty(oldField) && StringUtils.isNotEmpty(newField)) { + isUpdatedField = true; + } + if (StringUtils.isNotEmpty(oldField) && StringUtils.isNotEmpty(newField) && !oldField.equals(newField)) { + isUpdatedField = true; + } + return isUpdatedField; + } + + private static void logImmutableFieldUpdateWarning(String oldValue, String newValue, JsonPresentationFields field) { + log.warn("Update of the field {} of a policy not allowed. The change will be ignored. The old value is {} , the new value is {}. ", field, oldValue, newValue); + } + + private static Either validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy, Map policies) { + Either result = null; + Optional sameNamePolicy = Optional.empty(); + if (StringUtils.isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy + .getName()).matches()) { + log.error("Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), receivedPolicy.getUniqueId()); + result = Either.right(ActionStatus.INVALID_POLICY_NAME); + } + if (result == null && MapUtils.isNotEmpty(policies)) { + sameNamePolicy = policies.values() + .stream() + .filter(p -> p.getName().equals(receivedPolicy.getName())) + .findFirst(); + } + if (sameNamePolicy.isPresent()) { + log.error("Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ", receivedPolicy + .getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId()); + result = Either.right(ActionStatus.POLICY_NAME_ALREADY_EXIST); + } + if (result == null) { + validPolicy.setName(receivedPolicy.getName()); + result = Either.left(validPolicy); + } + return result; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java new file mode 100644 index 0000000000..ec5a1c3078 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java @@ -0,0 +1,118 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.List; + +/** + * Created by chaya on 10/18/2017. + */ +@org.springframework.stereotype.Component("serviceDistributionValidation") +public class ServiceDistributionValidation { + private static final Logger log = LoggerFactory.getLogger(ServiceDistributionValidation.class); + @Resource + private ComponentsUtils componentsUtils; + @Resource + private ToscaOperationFacade toscaOperationFacade; + @Resource + private UserValidations userValidations; + @Resource + private IDistributionEngine distributionEngine; + + public Either validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier, ServiceDistributionReqInfo data) { + try { + validateUserExists(modifier.getUserId()); + Service serviceToActivate = validateServiceExists(serviceUUID); + validateDistributionServiceLifeCycleState(serviceToActivate); + OperationalEnvironmentEntry operationalEnvironmentEntry = validateOperationalEnvExists(opEnvId); + String workloadContext = validateWorkloadContext(data); + ActivationRequestInformation activationRequestInformation = new ActivationRequestInformation(serviceToActivate, workloadContext, operationalEnvironmentEntry.getTenant()); + return Either.left(activationRequestInformation); + } catch (ValidationException e) { + log.error("failed while validating activate service UUID {} request. error {}", serviceUUID, e.getExceptionResponseFormat(), e); + return Either.right(e.getExceptionResponseFormat()); + } + } + + private Service validateServiceExists(String serviceUUID) { + if (StringUtils.isEmpty(serviceUUID.trim())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE); + throw new ValidationException(responseFormat); + } + Either latestComponentByUuid = toscaOperationFacade.getLatestServiceByUuid(serviceUUID); + if (latestComponentByUuid.isRight()) { + log.error("failed retrieving service {}", serviceUUID); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue()); + throw new ValidationException(responseFormat); + } + return (Service)latestComponentByUuid.left().value(); + } + + private String validateWorkloadContext(ServiceDistributionReqInfo data) { + String workloadContext = data.getWorkloadContext(); + if (workloadContext == null || workloadContext.isEmpty()) { + log.error("workload context does not exist on data to distribute"); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_BODY); + throw new ValidationException(responseFormat); + } + return workloadContext; + } + + private OperationalEnvironmentEntry validateOperationalEnvExists(String opEnvId) { + if (StringUtils.isEmpty(opEnvId.trim())) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE); + throw new ValidationException(responseFormat); + } + OperationalEnvironmentEntry operationalEnvironment = distributionEngine.getEnvironmentById(opEnvId); + if (operationalEnvironment == null) { + return failOnEnvNotExist(opEnvId); + } + if (!operationalEnvironment.getStatus().equals(EnvironmentStatusEnum.COMPLETED.getName())) { + log.error("the operational environment is not ready to receive distributions. environment status: {}", operationalEnvironment.getStatus()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND , ApiResourceEnum.ENVIRONMENT_ID.getValue()); + throw new ValidationException(responseFormat); + } + return operationalEnvironment; + } + + private OperationalEnvironmentEntry failOnEnvNotExist(String opEnvId) { + return ValidationUtils.throwValidationException(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue()), "failed to get operational environment {}", opEnvId); + } + + private void validateServiceState(Service service, List allowedStates) { + LifecycleStateEnum state = service.getLifecycleState(); + if (!allowedStates.contains(state)) { + log.error("service {} life cycle state {} is not valid for distribution", service.getUniqueId(), service.getLifecycleState()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_STATE); + throw new ValidationException(responseFormat); + } + } + private void validateUserExists(String userId) { + userValidations.validateUserExists(userId, "activate Distribution", false) + .left().on(responseFormat -> ValidationUtils.throwValidationException(responseFormat, "user {} not exist", userId)); + } + + private void validateDistributionServiceLifeCycleState(Service serviceToActivate) { + validateServiceState(serviceToActivate, + Arrays.asList(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFIED)); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java new file mode 100644 index 0000000000..e2e671f872 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.IUserBusinessLogic; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +@org.springframework.stereotype.Component +public class UserValidations { + + private static final Logger log = LoggerFactory.getLogger(UserValidations.class); + private final IUserBusinessLogic userAdmin; + private final ComponentsUtils componentsUtils; + + public UserValidations(IUserBusinessLogic userAdmin, ComponentsUtils componentsUtils) { + this.userAdmin = userAdmin; + this.componentsUtils = componentsUtils; + } + + public Either validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) { + Either eitherCreator = userAdmin.getUser(userId, inTransaction); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + ResponseFormat responseFormat; + if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + if (log.isDebugEnabled()) { + log.debug("validateUserExists - not authorized user, userId {}", userId); + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.AUTH_FAILED); + } else { + if (log.isDebugEnabled()) { + log.debug("validateUserExists - failed to authorize user, userId {}", userId); + } + responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value()); + } + if (log.isDebugEnabled()) { + log.debug("User is not listed. userId {}", userId); + } + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); + return Either.right(responseFormat); + } + return Either.left(eitherCreator.left().value()); + } + + public Either validateUserRole(User user, List roles) { + Role userRole = Role.valueOf(user.getRole()); + if (roles != null) { + if (!roles.contains(userRole)) { + if (log.isDebugEnabled()) { + log.debug("user is not in appropriate role to perform action"); + } + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + return Either.right(responseFormat); + } + return Either.left(Boolean.TRUE); + } + return Either.left(Boolean.FALSE); + } + + public Either validateUserExistsActionStatus(String userId, String ecompErrorContext) { + Either eitherCreator = userAdmin.getUser(userId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + log.debug("validateUserExists - not authorized user, userId {}", userId); + Either.right(ActionStatus.RESTRICTED_OPERATION); + } else { + log.debug("validateUserExists - failed to authorize user, userId {}", userId); + } + log.debug("User is not listed. userId {}", userId); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId); + return Either.right(eitherCreator.right().value()); + } + return Either.left(eitherCreator.left().value()); + } + + public Either validateUserNotEmpty(User user, String ecompErrorContext) { + String userId = user.getUserId(); + + if (StringUtils.isEmpty(userId)) { + log.debug("User header is missing "); + BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + return Either.right(responseFormat); + } + return Either.left(user); + } + + public Either validateUserExists(User user, String ecompErrorContext, boolean inTransaction) { + return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); + } + + public void validateUserExist(String userId, String ecompErrorContext, Wrapper errorWrapper) { + Either resp = validateUserExists(userId, ecompErrorContext, false); + if (resp.isRight()) { + errorWrapper.setInnerElement(resp.right().value()); + } + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java new file mode 100644 index 0000000000..8abf2f7d63 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.exception.ResponseFormat; + +/** + * Created by chaya on 10/18/2017. + */ +public class ValidationException extends RuntimeException { + + private transient ResponseFormat exceptionResponseFormat; + + public ValidationException(ResponseFormat exceptionResponseFormat) { + super(); + this.exceptionResponseFormat = exceptionResponseFormat; + } + + public ResponseFormat getExceptionResponseFormat() { + return exceptionResponseFormat; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java new file mode 100644 index 0000000000..07505a2adb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.components.validation; + +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ValidationUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(ValidationUtils.class); + + public static T throwValidationException(ResponseFormat responseFormat, String logMessage, Object ... logParams){ + LOGGER.error(logMessage, logParams); + throw new ValidationException(responseFormat); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java new file mode 100644 index 0000000000..967232ac86 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.Set; + +public class ForwardingPaths implements Serializable{ + + private static final long serialVersionUID=1L; + + public ForwardingPaths() { + } + + private Set forwardingPathToDelete; + public Set getForwardingPathToDelete() { + return forwardingPathToDelete; + } + + public void setForwardingPathToDelete(Set forwardingPathToDelete) { + this.forwardingPathToDelete = forwardingPathToDelete; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java new file mode 100644 index 0000000000..a033cec86f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java @@ -0,0 +1,89 @@ +package org.openecomp.sdc.be.datamodel; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +public class NameIdPair extends HashMap implements java.io.Serializable { + public static final String OPTIONS = "options"; + public static final String NAME = "name"; + public static final String ID = "id"; + public static final String OWNER_ID = "ownerId"; + + public NameIdPair(String name, String id) { + this(name, id, null); + } + + public NameIdPair(String name, String id, String ownerId) { + super(); + setId(id); + setName(name); + if (!Objects.isNull(ownerId)) { + setOwnerId(ownerId); + } + + } + + public NameIdPair(NameIdPair nameIdPair) { + super(nameIdPair); + } + + public String getName() { + return get(NAME).toString(); + } + + public void setName(String name) { + super.put(NAME, name); + } + + public String getId() { + return get(ID).toString(); + } + + public void setId(String id) { + super.put(ID, id); + } + + public String getOwnerId() { + return get(OWNER_ID).toString(); + } + + public void setOwnerId(String ownerId) { + put(OWNER_ID, ownerId); + } + + public Set getWrappedData() { + return (Set) super.get(OPTIONS); + } + + public void setWrappedData(Set data) { + super.put(OPTIONS, data); + } + + public void addWrappedData(NameIdPairWrapper nameIdPairWrapper) { + if (get(OPTIONS) == null) { + setWrappedData(new HashSet<>()); + } + getWrappedData().add(nameIdPairWrapper); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof NameIdPair)) return false; + NameIdPair that = (NameIdPair) o; + return Objects.equals(getId(), that.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } + + public static final NameIdPair create(String name, String id) { + return new NameIdPair(name, id); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java new file mode 100644 index 0000000000..e46e57705e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.HashMap; + +public class NameIdPairWrapper extends HashMap implements Serializable { + public static final String ID = "id"; + public static final String DATA = "data"; + + public NameIdPairWrapper() { + } + + public NameIdPairWrapper(NameIdPair nameIdPair) { + super(); + init(nameIdPair); + } + public void init(NameIdPair nameIdPair) { + setId(nameIdPair.getId()); + setData(new NameIdPair(nameIdPair)); + } + + public String getId() { + return get(ID).toString(); + } + + public void setId(String id) { + super.put(ID, id); + } + + public NameIdPair getData() { + return (NameIdPair) get(DATA); + } + + public void setData(NameIdPair data) { + put(DATA, data); + } + + public NameIdPair getNameIdPair(){ + return new NameIdPair(getData().getName(),getData().getId()); + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java new file mode 100644 index 0000000000..d05ddafed9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.datamodel; + +import java.io.Serializable; +import java.util.Set; + +public class ServiceRelations extends java.util.HashSet implements Serializable { + + + + public ServiceRelations() { + } + + public ServiceRelations(Set relations) { + super(); + addAll(relations); + } + + public Set getRelations() { + return this; + } + + public void setRelations(Set relations) { + clear(); + this.addAll(relations); + } + + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java index 921aefaa8e..855f20aba2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java @@ -24,16 +24,16 @@ import java.io.Serializable; public enum CategoryTypeEnum implements Serializable { - CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); + CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping"); - private String value; + private String value; - CategoryTypeEnum(String value) { - this.value = value; - } + CategoryTypeEnum(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java index 42ff4c900a..fc98400dd1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java @@ -22,6 +22,6 @@ package org.openecomp.sdc.be.datamodel.api; public enum HighestFilterEnum { - ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY; + ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java index 9f66911461..9f0d7a3281 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java @@ -20,39 +20,121 @@ package org.openecomp.sdc.be.datamodel.utils; +import org.apache.commons.codec.binary.Base64; +import org.openecomp.sdc.be.info.ArtifactTemplateInfo; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.stream.Collectors; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.common.api.ArtifactTypeEnum; - +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.util.ValidationUtils; public class ArtifactUtils { - public static ArtifactDefinition findMasterArtifact(Map deplymentArtifact, List artifacts, List artifactsList) { - for (String artifactUid : artifactsList) { - for (Entry entry : deplymentArtifact.entrySet()) { - ArtifactDefinition artifact = entry.getValue(); - if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) { - artifacts.add(artifact); - } - - } - } - if (artifacts.size() == 1) { - return artifacts.get(0); - } - ArtifactDefinition masterArtifact = null; - for (ArtifactDefinition artifactInfo : artifacts) { - String atrifactType = artifactInfo.getArtifactType(); - if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { - masterArtifact = artifactInfo; - continue; - } - if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - masterArtifact = artifactInfo; - break; - } - } - return masterArtifact; - } + + public static ArtifactDefinition findMasterArtifact(Map deplymentArtifact, List artifacts, List artifactsList) { + for (String artifactUid : artifactsList) { + for (Entry entry : deplymentArtifact.entrySet()) { + ArtifactDefinition artifact = entry.getValue(); + if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) { + artifacts.add(artifact); + } + + } + } + if (artifacts.size() == 1) { + return artifacts.get(0); + } + ArtifactDefinition masterArtifact = null; + for (ArtifactDefinition artifactInfo : artifacts) { + String atrifactType = artifactInfo.getArtifactType(); + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) { + masterArtifact = artifactInfo; + continue; + } + if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + masterArtifact = artifactInfo; + break; + } + } + return masterArtifact; + } + + public static Map buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, + ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, + byte[] artifactContentent, List updatedRequiredArtifacts, boolean isFromCsar) { + + Map json = new HashMap(); + if (artifactId != null && !artifactId.isEmpty()) + json.put(Constants.ARTIFACT_ID, artifactId); + + json.put(Constants.ARTIFACT_NAME, artifactName); + json.put(Constants.ARTIFACT_TYPE, artifactType); + json.put(Constants.ARTIFACT_DESCRIPTION, description); + json.put(Constants.IS_FROM_CSAR, isFromCsar); + + String encodedPayload = new String(artifactContentent); + + + encodedPayload = Base64.encodeBase64String(artifactContentent); + // } + + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType()); + json.put(Constants.REQUIRED_ARTIFACTS, + (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>() + : updatedRequiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) + || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()).collect(Collectors.toList())); + return json; + } + + public static Map buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, + byte[] artifactContentent, int atrifactLabelCounter) { + + Map json = new HashMap(); + String artifactName = artifactTemplateInfo.getFileName(); + + json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName()); + json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType()); + json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar"); + + String encodedPayload = Base64.encodeBase64String(artifactContentent); + + json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload); + String displayName = artifactName; + if (artifactName.lastIndexOf(".") > 0) + displayName = artifactName.substring(0, artifactName.lastIndexOf(".")); + json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName); + String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter); + json.put(Constants.ARTIFACT_LABEL, label); + json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType()); + List requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + json.put(Constants.REQUIRED_ARTIFACTS, + (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>() + : requiredArtifacts.stream() + .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) + || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())) + .map(e -> e.getFileName()).collect(Collectors.toList())); + return json; + } + + public static ArtifactDefinition findArtifactInList(List createdArtifacts, String artifactId) { + for (ArtifactDefinition artifact : createdArtifacts) { + if (artifact.getUniqueId().equals(artifactId)) { + return artifact; + } + } + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java index ab71508e62..cd6351cf9e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java @@ -25,52 +25,52 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; public class NodeTypeConvertUtils { - public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) { - NodeTypeEnum res = null; - if (componentTypeEnum != null) { - switch (componentTypeEnum) { - case SERVICE: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ServiceNewCategory; - break; + public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) { + NodeTypeEnum res = null; + if (componentTypeEnum != null) { + switch (componentTypeEnum) { + case SERVICE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ServiceNewCategory; + break; - default: - // doesn't support subcategories or grouping - break; - } - break; - case RESOURCE: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ResourceNewCategory; - break; - case SUBCATEGORY: - res = NodeTypeEnum.ResourceSubcategory; - break; - default: - // doesn't support grouping - break; - } - break; - case PRODUCT: - switch (categoryType) { - case CATEGORY: - res = NodeTypeEnum.ProductCategory; - break; - case SUBCATEGORY: - res = NodeTypeEnum.ProductSubcategory; - break; - case GROUPING: - res = NodeTypeEnum.ProductGrouping; - break; - } - break; - default: - break; - } - } - return res; - } + default: + // doesn't support subcategories or grouping + break; + } + break; + case RESOURCE: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ResourceNewCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ResourceSubcategory; + break; + default: + // doesn't support grouping + break; + } + break; + case PRODUCT: + switch (categoryType) { + case CATEGORY: + res = NodeTypeEnum.ProductCategory; + break; + case SUBCATEGORY: + res = NodeTypeEnum.ProductSubcategory; + break; + case GROUPING: + res = NodeTypeEnum.ProductGrouping; + break; + } + break; + default: + break; + } + } + return res; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java index f2a5b35562..624a8b623a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -20,236 +20,243 @@ package org.openecomp.sdc.be.datamodel.utils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; -import org.openecomp.sdc.be.ui.model.UiComponentMetadata; -import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; -import org.openecomp.sdc.be.ui.model.UiResourceMetadata; -import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; -import org.openecomp.sdc.be.ui.model.UiServiceMetadata; +import org.openecomp.sdc.be.ui.model.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; public class UiComponentDataConverter { - - public static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case INPUTS: - if(component.getInputs() == null){ - dataTransfer.setInputs(new ArrayList<>()); - } else { - dataTransfer.setInputs(component.getInputs()); - } - break; - - case COMPONENT_INSTANCE_RELATION: - if(component.getComponentInstancesRelations() == null){ - dataTransfer.setComponentInstancesRelations(new ArrayList<>()); - } else { - dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations()); - } - - break; - - case GROUPS: - if(component.getGroups() == null){ - dataTransfer.setGroups(new ArrayList<>()); - } else { - dataTransfer.setGroups(component.getGroups()); - } - break; - - case COMPONENT_INSTANCES: - if(component.getComponentInstances() == null) { - dataTransfer.setComponentInstances(new ArrayList<>()); - } else { - dataTransfer.setComponentInstances(component.getComponentInstances()); - } - break; - - case COMPONENT_INSTANCES_PROPERTIES: - if(component.getComponentInstancesProperties() == null) { - dataTransfer.setComponentInstancesProperties(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties()); - } - break; - - case CAPABILITIES: - if(component.getCapabilities() == null) { - dataTransfer.setCapabilities(new HashMap<>()); - } else { - dataTransfer.setCapabilities(component.getCapabilities()); - } - break; - - case REQUIREMENTS: - if(component.getRequirements() == null) { - dataTransfer.setRequirements(new HashMap<>()); - } else { - dataTransfer.setRequirements(component.getRequirements()); - } - break; - - case DEPLOYMENT_ARTIFACTS: - if(component.getDeploymentArtifacts() == null) { - dataTransfer.setDeploymentArtifacts(new HashMap<>()); - } else { - dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts()); - } - break; - - case TOSCA_ARTIFACTS: - if(component.getToscaArtifacts() == null) { - dataTransfer.setToscaArtifacts(new HashMap<>()); - } else { - dataTransfer.setToscaArtifacts(component.getToscaArtifacts()); - } - break; - - case ARTIFACTS: - if(component.getArtifacts() == null) { - dataTransfer.setArtifacts(new HashMap<>()); - } else { - dataTransfer.setArtifacts(component.getArtifacts()); - } - break; - - case COMPONENT_INSTANCES_ATTRIBUTES: - if(component.getComponentInstancesAttributes() == null) { - dataTransfer.setComponentInstancesAttributes(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes()); - } - break; - - case COMPONENT_INSTANCE_INPUTS: - if(component.getComponentInstancesInputs() == null) { - dataTransfer.setComponentInstancesInputs(new HashMap<>()); - } else { - dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs()); - } - - break; - - - default: - break; - } - - } - - - public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List paramsToReturn) { - UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); - - for(String fieldName: paramsToReturn){ - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case PROPERTIES: - if(resource.getProperties() == null) { - dataTransfer.setProperties(new ArrayList<>()); - } else { - dataTransfer.setProperties(resource.getProperties()); - } - break; - - case INTERFACES: - if(resource.getInterfaces() == null) { - dataTransfer.setInterfaces(new HashMap<>()); - } else { - dataTransfer.setInterfaces(resource.getInterfaces()); - } - break; - - case DERIVED_FROM: - if(resource.getDerivedFrom() == null) { - dataTransfer.setDerivedFrom(new ArrayList<>()); - } else { - dataTransfer.setDerivedFrom(resource.getDerivedFrom()); - } - break; - - case ATTRIBUTES: - if(resource.getAttributes() == null) { - dataTransfer.setAttributes(new ArrayList<>()); - } else { - dataTransfer.setAttributes(resource.getAttributes()); - } - break; - - case ADDITIONAL_INFORMATION: - if(resource.getAdditionalInformation() == null) { - dataTransfer.setAdditionalInformation(new ArrayList<>()); - } else { - dataTransfer.setAdditionalInformation(resource.getAdditionalInformation()); - } - break; - case METADATA: - UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); - dataTransfer.setMetadata(metadata); - break; - - default: - setUiTranferDataByFieldName(dataTransfer, resource, fieldName); - } - } - - return dataTransfer; - } - - public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List paramsToReturn) { - UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer(); - - for(String fieldName: paramsToReturn){ - - switch (ComponentFieldsEnum.findByValue(fieldName)) { - - case SERVICE_API_ARTIFACTS: - if(service.getServiceApiArtifacts() == null) { - dataTransfer.setServiceApiArtifacts(new HashMap<>()); - } else { - dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts()); - } - - break; - - case METADATA: - UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); - dataTransfer.setMetadata(metadata); - break; - default: - setUiTranferDataByFieldName(dataTransfer, service, fieldName); - } - } - - return dataTransfer; - } - - - public static UiComponentMetadata convertToUiComponentMetadata(Component component) { - - UiComponentMetadata uiComponentMetadata = null; - switch (component.getComponentType()) { - case RESOURCE: - Resource resource = (Resource)component; - uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); - break; - case SERVICE: - uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); - default: - - } - return uiComponentMetadata; - } + + private static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) { + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case INPUTS: + if(component.getInputs() == null){ + dataTransfer.setInputs(new ArrayList<>()); + } else { + dataTransfer.setInputs(component.getInputs()); + } + break; + + case COMPONENT_INSTANCE_RELATION: + if(component.getComponentInstancesRelations() == null){ + dataTransfer.setComponentInstancesRelations(new ArrayList<>()); + } else { + dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations()); + } + + break; + + case GROUPS: + if(component.getGroups() == null){ + dataTransfer.setGroups(new ArrayList<>()); + } else { + dataTransfer.setGroups(component.getGroups()); + } + break; + + case COMPONENT_INSTANCES: + if(component.getComponentInstances() == null) { + dataTransfer.setComponentInstances(new ArrayList<>()); + } else { + dataTransfer.setComponentInstances(component.getComponentInstances()); + } + break; + + case COMPONENT_INSTANCES_PROPERTIES: + if(component.getComponentInstancesProperties() == null) { + dataTransfer.setComponentInstancesProperties(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties()); + } + break; + + case CAPABILITIES: + if(component.getCapabilities() == null) { + dataTransfer.setCapabilities(new HashMap<>()); + } else { + dataTransfer.setCapabilities(component.getCapabilities()); + } + break; + + case POLICIES: + dataTransfer.setPolicies(component.resolvePoliciesList()); + break; + + case REQUIREMENTS: + if(component.getRequirements() == null) { + dataTransfer.setRequirements(new HashMap<>()); + } else { + dataTransfer.setRequirements(component.getRequirements()); + } + break; + + case DEPLOYMENT_ARTIFACTS: + if(component.getDeploymentArtifacts() == null) { + dataTransfer.setDeploymentArtifacts(new HashMap<>()); + } else { + dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts()); + } + break; + + case TOSCA_ARTIFACTS: + if(component.getToscaArtifacts() == null) { + dataTransfer.setToscaArtifacts(new HashMap<>()); + } else { + dataTransfer.setToscaArtifacts(component.getToscaArtifacts()); + } + break; + + case ARTIFACTS: + if(component.getArtifacts() == null) { + dataTransfer.setArtifacts(new HashMap<>()); + } else { + dataTransfer.setArtifacts(component.getArtifacts()); + } + break; + + case COMPONENT_INSTANCES_ATTRIBUTES: + if(component.getComponentInstancesAttributes() == null) { + dataTransfer.setComponentInstancesAttributes(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes()); + } + break; + + case COMPONENT_INSTANCE_INPUTS: + if(component.getComponentInstancesInputs() == null) { + dataTransfer.setComponentInstancesInputs(new HashMap<>()); + } else { + dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs()); + } + + break; + + + default: + break; + } + + } + + + public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List paramsToReturn) { + UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case PROPERTIES: + if(resource.getProperties() == null) { + dataTransfer.setProperties(new ArrayList<>()); + } else { + dataTransfer.setProperties(resource.getProperties()); + } + break; + + case INTERFACES: + if(resource.getInterfaces() == null) { + dataTransfer.setInterfaces(new HashMap<>()); + } else { + dataTransfer.setInterfaces(resource.getInterfaces()); + } + break; + + case DERIVED_FROM: + if(resource.getDerivedFrom() == null) { + dataTransfer.setDerivedFrom(new ArrayList<>()); + } else { + dataTransfer.setDerivedFrom(resource.getDerivedFrom()); + } + break; + + case ATTRIBUTES: + if(resource.getAttributes() == null) { + dataTransfer.setAttributes(new ArrayList<>()); + } else { + dataTransfer.setAttributes(resource.getAttributes()); + } + break; + + case ADDITIONAL_INFORMATION: + if(resource.getAdditionalInformation() == null) { + dataTransfer.setAdditionalInformation(new ArrayList<>()); + } else { + dataTransfer.setAdditionalInformation(resource.getAdditionalInformation()); + } + break; + case METADATA: + UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + + default: + setUiTranferDataByFieldName(dataTransfer, resource, fieldName); + } + } + + return dataTransfer; + } + + public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List paramsToReturn) { + UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer(); + + for(String fieldName: paramsToReturn){ + + switch (ComponentFieldsEnum.findByValue(fieldName)) { + + case SERVICE_API_ARTIFACTS: + if(service.getServiceApiArtifacts() == null) { + dataTransfer.setServiceApiArtifacts(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>()); + } else { + dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts()); + } + + break; + case FORWARDING_PATHS: + if(service.getForwardingPaths() == null) { + dataTransfer.setForwardingPaths(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>()); + } else { + dataTransfer.setForwardingPaths(service.getForwardingPaths()); + } + + break; + case METADATA: + UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); + dataTransfer.setMetadata(metadata); + break; + default: + setUiTranferDataByFieldName(dataTransfer, service, fieldName); + } + } + + return dataTransfer; + } + + + public static UiComponentMetadata convertToUiComponentMetadata(Component component) { + + UiComponentMetadata uiComponentMetadata = null; + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource)component; + uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + case SERVICE: + uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + default: + break; + } + return uiComponentMetadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java index 0cc415c80d..0aa8d5afa6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java @@ -27,39 +27,34 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; public class AuditHandler { - ComponentsUtils componentsUtils; - String instanceID; - private RegistrationRequest registrationRequest; + ComponentsUtils componentsUtils; + String instanceID; + private RegistrationRequest registrationRequest; - public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { - super(); - this.componentsUtils = componentsUtils; - this.instanceID = instanceID; - this.registrationRequest = registrationRequest; - } + public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) { + super(); + this.componentsUtils = componentsUtils; + this.instanceID = instanceID; + this.registrationRequest = registrationRequest; + } - public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); - } + public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) { - String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()) - : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()); - componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, String topicName) { + componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode())); + } - } + public void auditRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - public void auditRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } - } - - public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { - componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), - registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); - } + public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) { + componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), + registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName())); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java index ae1de21ea8..2c2adaa970 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java @@ -20,224 +20,275 @@ package org.openecomp.sdc.be.distribution; -import java.util.List; - -import javax.annotation.Resource; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.http.HttpStatus; -import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; -import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; -import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; -import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum; +import org.openecomp.sdc.be.components.distribution.engine.*; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; -import org.openecomp.sdc.be.distribution.api.client.ServerListResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; -import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.be.distribution.api.client.*; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Resource; +import javax.ws.rs.core.Response; +import java.util.List; -import fj.data.Either; +import static org.apache.commons.lang.BooleanUtils.isTrue; +import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName; +import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager; @Component("distributionBusinessLogic") public class DistributionBusinessLogic { - public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; - public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static Logger log = LoggerFactory.getLogger(DistributionBusinessLogic.class.getName()); - @Resource - private DistributionEngine distributionEngine; - - private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); - private CambriaHandler cambriaHandler; - - public Either getUebServerList() { - - DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - - List serverList = distributionEngineConfiguration.getUebServers(); - - if (serverList != null && !serverList.isEmpty()) { - - ServerListResponse serverListResponse = new ServerListResponse(); - - serverListResponse.setUebServerList(serverList); - - return Either.left(serverListResponse); - } else { - ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(errorResponseWrapper); - } - - } - - public void handleRegistration(Wrapper responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) { - CambriaErrorResponse registerResponse = null; - try { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER); - - if (responseWrapper.isEmpty()) { - registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER); - // Second Register failed - unregister the first - if (!responseWrapper.isEmpty()) { - CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER); - } - } - - if (responseWrapper.isEmpty()) { - TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - } finally { - auditHandler.auditRegisterRequest(registerResponse); - } - } - - public void handleUnRegistration(Wrapper responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) { - Wrapper cambriaResponseWrapper = new Wrapper<>(); - try { - CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.PRODUCER); - auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); - - CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.CONSUMER); - auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER); - updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); - - // Success unregister both topics - TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), getStatusTopicName(unRegistrationRequest.getDistrEnvName()), - unregisterClientConsumerTopicResponse.getOperationStatus(), unregisterClientProducerTopicResponse.getOperationStatus()); - - if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed"); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration of subscriber to topic"); - Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - - } finally { - auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); - } - } - - private void updateResponseWrapper(Wrapper cambriaResponseWrapper, CambriaErrorResponse currentResponse) { - if (cambriaResponseWrapper.isEmpty()) { - cambriaResponseWrapper.setInnerElement(currentResponse); - } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { - cambriaResponseWrapper.setInnerElement(currentResponse); - - } - - } - - public static String getNotificationTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); - - } - - public static String getStatusTopicName(String envName) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); - - } - - protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName; - if (subscriberType == SubscriberTypeEnum.PRODUCER) { - topicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); - } else { - topicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); - - } - log.debug("unregistering client as {} , from topic: {}", subscriberType.name(), topicName); - return getCambriaHandler().unRegisterFromTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType); - } - - private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - - TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); - topicResponse.setDistrNotificationTopicName(notificationTopicName); - topicResponse.setDistrStatusTopicName(statusTopicName); - return topicResponse; - } - - protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper responseWrapper, RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType) { - DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration(); - String topicName, errorMsg; - - // Register for notifications as consumer - if (subscriberType == SubscriberTypeEnum.CONSUMER) { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; - } - // Register for status as producer - else { - topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; - } - log.debug("registering client as {} , from topic: {}", subscriberType.name(), topicName); - CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), subscriberType); - - if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { - Response failedRegistrationResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg); - responseWrapper.setInnerElement(failedRegistrationResponse); - } - return registerToTopic; - } - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; - } - - public ResponseFormatManager getResponseFormatManager() { - return responseFormatManager; - } - - public DistributionEngine getDistributionEngine() { - return distributionEngine; - } - - public CambriaHandler getCambriaHandler() { - if (cambriaHandler == null) { - cambriaHandler = new CambriaHandler(); - } - return cambriaHandler; - } + public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine"; + public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine"; + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger LOGGER = LoggerFactory.getLogger(DistributionBusinessLogic.class); + @Resource + private IDistributionEngine distributionEngine; + + private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); + private CambriaHandler cambriaHandler; + + private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) { + if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){ + registrationRequest.setDistEnvEndPoints(config.getUebServers()); + } + } + public Either getUebServerList() { + + DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + + List serverList = distributionEngineConfiguration.getUebServers(); + + if (serverList != null && !serverList.isEmpty()) { + + ServerListResponse serverListResponse = new ServerListResponse(); + + serverListResponse.setUebServerList(serverList); + + return Either.left(serverListResponse); + } else { + ResponseFormat errorResponseWrapper = getResponseFormatManager() + .getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(errorResponseWrapper); + } + + } + + public void handleRegistration(Wrapper responseWrapper, RegistrationRequest registrationRequest, + AuditHandler auditHandler) { + CambriaErrorResponse registerResponse = null; + try { + DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration(); + String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty(); + + // Story [347698] Distribution Client Get Indication from + // component whether to register as consumer and producer on + // status topic + boolean registeredAsConsumerOnStatus = false; + if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) { + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + registeredAsConsumerOnStatus = responseWrapper.isEmpty(); + + } + + if (responseWrapper.isEmpty()) { + String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, + SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, notificationTopicName); + } + // Unregister Rollback + if (!responseWrapper.isEmpty()) { + if (isRegisteredAsProducerOnStatusSuccess) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, statusTopicName); + } + if (registeredAsConsumerOnStatus) { + CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, + SubscriberTypeEnum.CONSUMER, statusTopicName); + auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, statusTopicName); + } + } + + if (responseWrapper.isEmpty()) { + TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + } + + } catch (Exception e) { + LOGGER.error("registration to topic failed", e); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + "registration of subscriber to topic"); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + } finally { + auditHandler.auditRegisterRequest(registerResponse); + } + } + + public void handleUnRegistration(Wrapper responseWrapper, RegistrationRequest unRegistrationRequest, + AuditHandler auditHandler) { + Wrapper cambriaResponseWrapper = new Wrapper<>(); + try { + String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName); + auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER, + statusTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse); + + String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName()); + CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic( + unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName); + auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER, + notificationTopicName); + updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse); + + // Success unregister both topics + TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse( + getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), + getStatusTopicName(unRegistrationRequest.getDistrEnvName()), + unregisterClientConsumerTopicResponse.getOperationStatus(), + unregisterClientProducerTopicResponse.getOperationStatus()); + + if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) { + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build()); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, + "unregistration failed"); + responseWrapper.setInnerElement( + Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build()); + } + } catch (Exception e) { + LOGGER.error("unregistered to topic failed", e); + Response errorResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + + } finally { + auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement()); + } + } + + private void updateResponseWrapper(Wrapper cambriaResponseWrapper, + CambriaErrorResponse currentResponse) { + if (cambriaResponseWrapper.isEmpty()) { + cambriaResponseWrapper.setInnerElement(currentResponse); + } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) { + cambriaResponseWrapper.setInnerElement(currentResponse); + + } + + } + + public static String getNotificationTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName); + + } + + public static String getStatusTopicName(String envName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName); + + } + + protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, + SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(unRegistrationRequest, config); + + LOGGER.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints()); + return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(), + config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName); + } + + private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + + TopicRegistrationResponse topicResponse = new TopicRegistrationResponse(); + topicResponse.setDistrNotificationTopicName(notificationTopicName); + topicResponse.setDistrStatusTopicName(statusTopicName); + return topicResponse; + } + + protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper responseWrapper, + RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) { + DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager() + .getDistributionEngineConfiguration(); + initRequestEnvEndPoints(registrationRequest, config); + String errorMsg; + + // Register for notifications as consumer + if (subscriberType == SubscriberTypeEnum.CONSUMER) { + errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed"; + } + // Register for status as producer + else { + errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed"; + } + LOGGER.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints()); + CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + subscriberType, topicName); + + if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) { + Response failedRegistrationResponse = buildErrorResponse( + getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, + errorMsg); + responseWrapper.setInnerElement(failedRegistrationResponse); + } + return registerToTopic; + } + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { + return Response.status(requestErrorWrapper.getStatus()) + .entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + } + + public ResponseFormatManager getResponseFormatManager() { + return responseFormatManager; + } + + public IDistributionEngine getDistributionEngine() { + return distributionEngine; + } + + public CambriaHandler getCambriaHandler() { + if (cambriaHandler == null) { + cambriaHandler = new CambriaHandler(); + } + return cambriaHandler; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java index a6a6602cb0..3edb3d8f69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java @@ -21,5 +21,5 @@ package org.openecomp.sdc.be.distribution.api.client; public enum CambriaOperationStatus { - OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, + OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR, } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java index ef14efe4f8..1dfbdb538d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java @@ -20,21 +20,43 @@ package org.openecomp.sdc.be.distribution.api.client; +import java.util.List; + public class RegistrationRequest { - String apiPublicKey; - String distrEnvName; + String apiPublicKey; + String distrEnvName; + Boolean isConsumerToSdcDistrStatusTopic; + List distEnvEndPoints; + + public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic) { + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + public RegistrationRequest(String apiPublicKey, String distrEnvName, List distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){ + this.apiPublicKey = apiPublicKey; + this.distrEnvName = distrEnvName; + this.distEnvEndPoints = distEnvEndPoints; + this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic; + } + + public String getApiPublicKey() { + return apiPublicKey; + } - public RegistrationRequest(String apiPublicKey, String distrEnvName) { - this.apiPublicKey = apiPublicKey; - this.distrEnvName = distrEnvName; - } + public String getDistrEnvName() { + return distrEnvName; + } - public String getApiPublicKey() { - return apiPublicKey; - } + public Boolean getIsConsumerToSdcDistrStatusTopic() { + return isConsumerToSdcDistrStatusTopic; + } + public List getDistEnvEndPoints() { + return distEnvEndPoints; + } - public String getDistrEnvName() { - return distrEnvName; - } + public void setDistEnvEndPoints(List distEnvEndPoints) { + this.distEnvEndPoints = distEnvEndPoints; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java index 267a691e29..2eebedfd7c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java @@ -24,13 +24,13 @@ import java.util.List; public class ServerListResponse { - private List uebServerList; + private List uebServerList; - public List getUebServerList() { - return uebServerList; - } + public List getUebServerList() { + return uebServerList; + } - public void setUebServerList(List uebServerList) { - this.uebServerList = uebServerList; - } + public void setUebServerList(List uebServerList) { + this.uebServerList = uebServerList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java index e2a34a19d5..5d1b0657c6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java @@ -21,22 +21,22 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicRegistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; + String distrNotificationTopicName; + String distrStatusTopicName; - public void setDistrNotificationTopicName(String distrNotificationTopicName) { - this.distrNotificationTopicName = distrNotificationTopicName; - } + public void setDistrNotificationTopicName(String distrNotificationTopicName) { + this.distrNotificationTopicName = distrNotificationTopicName; + } - public void setDistrStatusTopicName(String distrStatusTopicName) { - this.distrStatusTopicName = distrStatusTopicName; - } + public void setDistrStatusTopicName(String distrStatusTopicName) { + this.distrStatusTopicName = distrStatusTopicName; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java index ffb9f9352f..621cd37a54 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java @@ -21,32 +21,32 @@ package org.openecomp.sdc.be.distribution.api.client; public class TopicUnregistrationResponse { - String distrNotificationTopicName; - String distrStatusTopicName; - CambriaOperationStatus notificationUnregisterResult; - CambriaOperationStatus statusUnregisterResult; + String distrNotificationTopicName; + String distrStatusTopicName; + CambriaOperationStatus notificationUnregisterResult; + CambriaOperationStatus statusUnregisterResult; - public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { - super(); - this.distrNotificationTopicName = distrNotificationTopicName; - this.distrStatusTopicName = distrStatusTopicName; - this.notificationUnregisterResult = notificationUnregisterResult; - this.statusUnregisterResult = statusUnregisterResult; - } + public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) { + super(); + this.distrNotificationTopicName = distrNotificationTopicName; + this.distrStatusTopicName = distrStatusTopicName; + this.notificationUnregisterResult = notificationUnregisterResult; + this.statusUnregisterResult = statusUnregisterResult; + } - public String getDistrNotificationTopicName() { - return distrNotificationTopicName; - } + public String getDistrNotificationTopicName() { + return distrNotificationTopicName; + } - public String getDistrStatusTopicName() { - return distrStatusTopicName; - } + public String getDistrStatusTopicName() { + return distrStatusTopicName; + } - public CambriaOperationStatus getNotificationUnregisterResult() { - return notificationUnregisterResult; - } + public CambriaOperationStatus getNotificationUnregisterResult() { + return notificationUnregisterResult; + } - public CambriaOperationStatus getStatusUnregisterResult() { - return statusUnregisterResult; - } + public CambriaOperationStatus getStatusUnregisterResult() { + return statusUnregisterResult; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java index 125c1012b2..984a831c8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java @@ -20,45 +20,33 @@ package org.openecomp.sdc.be.distribution.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; import org.openecomp.sdc.be.servlets.BeGenericServlet; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; /** * This Servlet serves external users to download artifacts. @@ -73,249 +61,233 @@ import io.swagger.annotations.ApiResponses; @Singleton public class DistributionCatalogServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - @Context - private HttpServletRequest request; + private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class); + @Context + private HttpServletRequest request; + + // ******************************************************* + // Download (GET) artifacts + // **********************************************************/ + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadServiceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("artifactName") final String artifactName) { + + Response response = null; + String requestURI = request.getRequestURI(); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); - // ******************************************************* - // Download (GET) artifacts - // **********************************************************/ - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadServiceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Map headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceName + * @param resourceVersion + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadResourceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceName") final String resourceName, + @PathParam("resourceVersion") final String resourceVersion, + @PathParam("artifactName") final String artifactName) { - Map headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + Response response = null; + String requestURI = request.getRequestURI(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download Murano package artifact for service - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceName - * @param resourceVersion - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadResourceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceName") final String resourceName, - @PathParam("resourceVersion") final String resourceVersion, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param serviceName + * @param serviceVersion + * @param resourceInstanceName + * @param artifactName + * @return + */ + @GET + @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), + @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), + @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), + @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response downloadResourceInstanceArtifact( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @PathParam("serviceName") final String serviceName, + @PathParam("serviceVersion") final String serviceVersion, + @PathParam("resourceInstanceName") final String resourceInstanceName, + @PathParam("artifactName") final String artifactName) { - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param serviceName - * @param serviceVersion - * @param resourceInstanceName - * @param artifactName - * @return - */ - @GET - @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(nickname = "downloadResourceInstanceArtifactByName",value = "Download resource instance artifact by artifact name", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"), - @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"), - @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"), - @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response downloadResourceInstanceArtifact( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @PathParam("serviceName") final String serviceName, - @PathParam("serviceVersion") final String serviceVersion, - @PathParam("resourceInstanceName") final String resourceInstanceName, - @PathParam("artifactName") final String artifactName) { - - Response response = null; - String requestURI = request.getRequestURI(); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD; - EnumMap additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + Response response = null; + String requestURI = request.getRequestURI(); - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("Missing X-ECOMP-InstanceID header"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("Missing X-ECOMP-InstanceID header"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + return buildErrorResponse(responseFormat); + } - try { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); - if (downloadRsrcArtifactEither.isRight()) { - ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = downloadRsrcArtifactEither.left().value(); - // Returning 64-encoded as it was received during upload - InputStream is = new ByteArrayInputStream(value); - Map headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; + try { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName); + if (downloadRsrcArtifactEither.isRight()) { + ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value(); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = downloadRsrcArtifactEither.left().value(); + // Returning 64-encoded as it was received during upload + InputStream is = new ByteArrayInputStream(value); + Map headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName)); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI)); + response = buildOkResponse(responseFormat, is, headers); + } + return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); - log.debug("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API"); + log.debug("download artifact failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java index 6add877fe0..b5c322f90b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java @@ -20,20 +20,9 @@ package org.openecomp.sdc.be.distribution.servlet; -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.distribution.AuditHandler; @@ -56,17 +45,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.ResponseHeader; +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * This Servlet serves external users for distribution purposes. @@ -81,321 +67,315 @@ import io.swagger.annotations.ResponseHeader; @Singleton public class DistributionServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionServlet.class.getName()); - @Resource - private DistributionBusinessLogic distributionLogic; - @Context - private HttpServletRequest request; - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param authorization - * @return - */ - @GET - @Path("/distributionUebCluster") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", - //TODO Tal G fix response headers - responseHeaders = { - @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), - @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getUebServerList( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - if (instanceId == null) { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - response = buildErrorResponse(responseFormat); - getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - } - - try { - Either actionResponse = distributionLogic.getUebServerList(); - - if (actionResponse.isRight()) { - responseFormat = actionResponse.right().value(); - response = buildErrorResponse(responseFormat); - } else { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - } - - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "failed to get ueb serbver list from cofiguration"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); - log.debug("failed to get ueb serbver list from cofiguration", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - response = buildErrorResponse(responseFormat); - return response; - } - - } - - /** - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/registerForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - //TODO Tal G fix response headers and to check missing header validations with Michael L - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response registerForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper responseWrapper = new Wrapper<>(); - Wrapper registrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, registrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - - if (responseWrapper.isEmpty()) { - distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - /** - * Returns list of valid artifact types for validation done in the distribution client.
- * The list is the representation of the values of the enum ArtifactTypeEnum. - * - * @param requestId - * @param instanceId - * @param authorization - * @param accept - * @return - */ - @GET - @Path("/artifactTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - public Response getValidArtifactTypes( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - - Wrapper responseWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); - if (responseWrapper.isEmpty()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); - } else { - response = responseWrapper.getInnerElement(); - } - return response; - } - - /** - * Removes from subscription for distribution notifications - * - * @param requestId - * @param instanceId - * @param accept - * @param contenType - * @param contenLength - * @param authorization - * @param requestJson - * @return - */ - @POST - @Path("/unRegisterForDistribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") - //TODO Edit the responses - @ApiResponses(value = { - @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 400, message = "Missing Body - POL4500"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), - @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), - @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact") - public Response unRegisterForDistribution( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - String requestJson) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - init(request); - - Wrapper responseWrapper = new Wrapper<>(); - Wrapper unRegistrationRequestWrapper = new Wrapper<>(); - - validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); - - if (responseWrapper.isEmpty()) { - validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); - } - if (responseWrapper.isEmpty()) { - validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); - } - if (responseWrapper.isEmpty()) { - distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); - } - - return responseWrapper.getInnerElement(); - } - - private void validateEnv(Wrapper responseWrapper, String distrEnvName) { - - // DE194021 - StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); - // DE194021 - // StorageOperationStatus environmentStatus = - // distributionLogic.getDistributionEngine().isEnvironmentAvailable(distrEnvName); - if (environmentStatus != StorageOperationStatus.OK) { - if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); - responseWrapper.setInnerElement(missingHeaderResponse); - } else { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(missingHeaderResponse); - } - } - - } - - private void init(HttpServletRequest request) { - if (distributionLogic == null) { - distributionLogic = getDistributionBL(request.getSession().getServletContext()); - } - } - - private void validateHeaders(Wrapper responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { - if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { - Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); - responseWrapper.setInnerElement(missingHeaderResponse); - // Audit - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); - - } - - } - - private void validateJson(Wrapper responseWrapper, Wrapper registrationRequestWrapper, String requestJson) { - if (requestJson == null || requestJson.isEmpty()) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - Either eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); - if (eitherRegistration.isLeft()) { - RegistrationRequest registrationRequest = eitherRegistration.left().value(); - if (registrationRequest.getApiPublicKey() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); - responseWrapper.setInnerElement(missingBodyResponse); - - } else if (registrationRequest.getDistrEnvName() == null) { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); - responseWrapper.setInnerElement(missingBodyResponse); - } else { - registrationRequestWrapper.setInnerElement(registrationRequest); - } - } else { - Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); - responseWrapper.setInnerElement(missingBodyResponse); - } - } - - } - - private DistributionBusinessLogic getDistributionBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(DistributionBusinessLogic.class); - } - - private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { - return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); - } + private static final Logger log = LoggerFactory.getLogger(DistributionServlet.class); + @Resource + private DistributionBusinessLogic distributionLogic; + @Context + private HttpServletRequest request; + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param authorization + * @return + */ + @GET + @Path("/distributionUebCluster") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List", + //TODO Tal G fix response headers + responseHeaders = { + @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class), + @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getUebServerList( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + if (instanceId == null) { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + response = buildErrorResponse(responseFormat); + getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + } + + try { + Either actionResponse = distributionLogic.getUebServerList(); + + if (actionResponse.isRight()) { + responseFormat = actionResponse.right().value(); + response = buildErrorResponse(responseFormat); + } else { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + } + + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration"); + log.debug("failed to get ueb serbver list from cofiguration", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + response = buildErrorResponse(responseFormat); + return response; + } + + } + + /** + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/registerForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + //TODO Tal G fix response headers and to check missing header validations with Michael L + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response registerForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper responseWrapper = new Wrapper<>(); + Wrapper registrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, registrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + + if (responseWrapper.isEmpty()) { + distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + /** + * Returns list of valid artifact types for validation done in the distribution client.
+ * The list is the representation of the values of the enum ArtifactTypeEnum. + * + * @param requestId + * @param instanceId + * @param authorization + * @param accept + * @return + */ + @GET + @Path("/artifactTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + public Response getValidArtifactTypes( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) { + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + + Wrapper responseWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES); + if (responseWrapper.isEmpty()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values()); + } else { + response = responseWrapper.getInnerElement(); + } + return response; + } + + /** + * Removes from subscription for distribution notifications + * + * @param requestId + * @param instanceId + * @param accept + * @param contenType + * @param contenLength + * @param authorization + * @param requestJson + * @return + */ + @POST + @Path("/unRegisterForDistribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications") + //TODO Edit the responses + @ApiResponses(value = { + @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 400, message = "Missing Body - POL4500"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"), + @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"), + @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")}) + public Response unRegisterForDistribution( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + String requestJson) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + init(request); + + Wrapper responseWrapper = new Wrapper<>(); + Wrapper unRegistrationRequestWrapper = new Wrapper<>(); + + validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL); + + if (responseWrapper.isEmpty()) { + validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson); + } + if (responseWrapper.isEmpty()) { + validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName()); + } + if (responseWrapper.isEmpty()) { + distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement())); + } else { + BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed"); + } + + return responseWrapper.getInnerElement(); + } + + private void validateEnv(Wrapper responseWrapper, String distrEnvName) { + + // DE194021 + StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable(); + if (environmentStatus != StorageOperationStatus.OK) { + if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST)); + responseWrapper.setInnerElement(missingHeaderResponse); + } else { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(missingHeaderResponse); + } + } + + } + + private void init(HttpServletRequest request) { + if (distributionLogic == null) { + distributionLogic = getDistributionBL(request.getSession().getServletContext()); + } + } + + private void validateHeaders(Wrapper responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) { + if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) { + Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID)); + responseWrapper.setInnerElement(missingHeaderResponse); + // Audit + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage()); + + } + + } + + private void validateJson(Wrapper responseWrapper, Wrapper registrationRequestWrapper, String requestJson) { + if (requestJson == null || requestJson.isEmpty()) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + Either eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class); + if (eitherRegistration.isLeft()) { + RegistrationRequest registrationRequest = eitherRegistration.left().value(); + if (registrationRequest.getApiPublicKey() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY)); + responseWrapper.setInnerElement(missingBodyResponse); + + } else if (registrationRequest.getDistrEnvName() == null) { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME)); + responseWrapper.setInnerElement(missingBodyResponse); + } else { + registrationRequestWrapper.setInnerElement(registrationRequest); + } + } else { + Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY)); + responseWrapper.setInnerElement(missingBodyResponse); + } + } + + } + + private DistributionBusinessLogic getDistributionBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(DistributionBusinessLogic.class); + } + + private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) { + return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java new file mode 100644 index 0000000000..28621bcb41 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.dto; + +/** + * Created by yavivi on 18/02/2018. + */ +public class ExternalRefDTO { + private String referenceUUID; + + public ExternalRefDTO(){ + //Empty constructor for serialization purposes + } + + public ExternalRefDTO(String ref){ + this.referenceUUID = ref; + } + + public String getReferenceUUID() { + return referenceUUID; + } + + public void setReferenceUUID(String referenceUUID) { + this.referenceUUID = referenceUUID; + } + + @Override + public String toString() { + return this.referenceUUID; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java index c88ec87d58..6ffa3a7c34 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.ecomp; -import java.util.LinkedList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - +import fj.data.Either; import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; import org.openecomp.portalsdk.core.restful.domain.EcompRole; @@ -44,343 +40,342 @@ import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import java.util.LinkedList; +import java.util.List; + -/* - * PortalAPIException(String message, Throwable cause); - */ public class EcompIntImpl implements IPortalRestAPIService { - private static Logger log = LoggerFactory.getLogger(EcompIntImpl.class.getName()); - - public EcompIntImpl() { - log.debug("EcompIntImpl Class Instantiated"); - } - - @Override - public void pushUser(EcompUser user) throws PortalAPIException { - log.debug("Start handle request of ECOMP pushUser"); - try { - if (user == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO); - log.debug("Recieved null for argument user"); - throw new PortalAPIException("Recieved null for argument user"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - final String modifierAttId = "jh0003"; - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - Either newASDCUser = EcompUserConverter.convertEcompUserToUser(user); - if (newASDCUser.isRight()) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO); - log.debug("Failed to create user {}", user.toString()); - throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); - } else if (newASDCUser.left().value() == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); - log.debug("Failed to create user {}", user.toString()); - throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); - } - - User convertedAsdcUser = newASDCUser.left().value(); - Either createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser); - - // ALREADY EXIST ResponseFormat - final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006"; - - if (createUserResponse.isRight()) { - if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) { - log.debug("Failed to create user {}", user.toString()); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to create user" + createUserResponse.right()); - } - log.debug("User already exist {}", user.toString()); - } - log.debug("User created {}", user.toString()); - } catch (Exception e) { - log.debug("Failed to create user {}", user, e); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to create user", e); - } - } - - /* - * (non-Javadoc) - * - * - * loginId - equals to userId - * - */ - @Override - public void editUser(String loginId, EcompUser user) throws PortalAPIException { - log.debug("Start handle request of ECOMP editUser"); - - try { - if (user == null) { - log.debug("Recieved null for argument user"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument user"); - } else if (loginId == null) { - log.debug("Recieved null for argument loginId"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument loginId"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { - log.debug("loginId and user loginId not equal"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO); - throw new PortalAPIException("loginId not equals to the user loginId field"); - } else if (user.getLoginId() == null) { - user.setLoginId(loginId); - } - - Either asdcUser = EcompUserConverter.convertEcompUserToUser(user); - if (asdcUser.isRight()) { - log.debug("Failed to convert user"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO); - throw new PortalAPIException(asdcUser.right().value()); - } else if (asdcUser.left().value() == null) { - log.debug("NULL pointer returned from user converter"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to edit user"); - } - - Either updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value()); - - if (updateUserCredentialsResponse.isRight()) { - log.debug("Failed to updateUserCredentials"); - BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value()); - } - } catch (Exception e) { - log.debug("Failed to updateUserCredentials"); - throw new PortalAPIException("Failed to edit user", e); - } - - } - - @Override - public EcompUser getUser(String loginId) throws PortalAPIException { - log.debug("Start handle request of ECOMP getUser"); - - try { - - if (loginId == null) { - log.debug("Recieved null for argument loginId"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO); - throw new PortalAPIException("Recieved null for argument loginId"); - } - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - Either getUserResponse = userBusinessLogic.getUser(loginId, false); - - if (getUserResponse.isRight()) { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get User" + getUserResponse.right()); - } else { - if (getUserResponse.left().value() != null) { - Either ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); - if (ecompUser.isLeft() && ecompUser.left().value() != null) { - return ecompUser.left().value(); - } else { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException(ecompUser.right().value()); - } - } else { - log.debug("Failed to get User"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get User" + getUserResponse.right()); - } - } - } catch (Exception e) { - log.debug("Failed to get User"); - throw new PortalAPIException("Failed to get User", e); - } - } - - @Override - public List getUsers() throws PortalAPIException { - log.debug("Start handle request of ECOMP getUsers"); - - try { - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - final String modifierAttId = "jh0003"; - - Either, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null); - - if (getUsersResponse.isRight()) { - log.debug("Failed to get Users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); - } else { - if (getUsersResponse.left().value() != null) { - List ecompUserList = new LinkedList<>(); - for (User user : getUsersResponse.left().value()) { - Either ecompUser = EcompUserConverter.convertUserToEcompUser(user); - if (ecompUser.isRight()) { - log.debug("Failed to convert User {}", user); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); - continue; - } else if (ecompUser.left().value() == null) { - log.debug("Failed to convert User {}", user); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); - continue; - } - ecompUserList.add(ecompUser.left().value()); - } - return ecompUserList; - } else { - log.debug("Failed to get users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); - } - } - } catch (Exception e) { - log.debug("Failed to get users"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Users", e); - } - } - - @Override - public List getAvailableRoles() throws PortalAPIException { - log.debug("Start handle request of ECOMP getAvailableRoles"); - try { - List ecompRolesList = new LinkedList<>(); - for (Role role : Role.values()) { - EcompRole ecompRole = new EcompRole(); - ecompRole.setId(new Long(role.ordinal())); - ecompRole.setName(role.name()); - ecompRolesList.add(ecompRole); - } - - if (ecompRolesList.isEmpty()) { - throw new PortalAPIException(); - } - - return ecompRolesList; - } catch (Exception e) { - log.debug("Failed to fetch roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO); - throw new PortalAPIException("Roles fetching failed", e); - } - - } - - /** - * The user role updated through this method only - */ - @Override - public void pushUserRole(String loginId, List roles) throws PortalAPIException { - log.debug("Start handle request of ECOMP pushUserRole"); - - final String modifierAttId = "jh0003"; - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - String updatedRole = null; - - if (roles == null) { - throw new PortalAPIException("Error: Recieved null for roles"); - } else if (roles.iterator().hasNext()) { - EcompRole ecompRole = roles.iterator().next(); - updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole); - log.debug("pushing role: {} to user: {}", updatedRole, loginId); - Either updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); - if (updateUserRoleResponse.isRight()) { - log.debug("Error: Failed to update role"); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); - } - } else { - log.debug("Error: No roles in List"); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO); - //throw new PortalAPIException("Error: No roles in List"); - //in this cases we want to deactivate the user - Either deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId); - if (deActivateUserResponse.isRight()) { - log.debug("Error: Failed to deactivate user {}",loginId); - BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO); - throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage()); - } - } - } - - @Override - public List getUserRoles(String loginId) throws PortalAPIException { - try { - log.debug("Start handle request of ECOMP getUserRoles"); - - UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); - - Either getUserResponse = userBusinessLogic.getUser(loginId, false); - - if (getUserResponse.isRight()) { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); - } else { - if (getUserResponse.left().value() != null) { - Either ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); - if (ecompUser.isRight()) { - log.debug("Error: Failed to convert Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); - throw new PortalAPIException(ecompUser.right().value()); - } else if (ecompUser.left().value() == null) { - log.debug("Error: Failed to convert Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); - throw new PortalAPIException(); - } - - return new LinkedList<>(ecompUser.left().value().getRoles()); - } else { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR); - throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); - } - } - } catch (Exception e) { - log.debug("Error: Failed to get Roles"); - BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); - throw new PortalAPIException("Failed to get Roles", e); - } - } - - @Override - public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { - // TODO Validation should be changed completely - final String USERNAME = request.getHeader("username"); - final String PASSWORD = request.getHeader("password"); - - if (USERNAME != null && PASSWORD != null) { - if (!USERNAME.equals("") && !PASSWORD.equals("")) { - log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD); - return true; - } - } - - log.debug("User authentication failed"); - return false; - } - - private UserBusinessLogic getUserBusinessLogic() { - ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); - UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); - return userBusinessLogic; - } - - /** + private static final Logger log = LoggerFactory.getLogger(EcompIntImpl.class); + + public EcompIntImpl() { + log.debug("EcompIntImpl Class Instantiated"); + } + + @Override + public void pushUser(EcompUser user) throws PortalAPIException { + log.debug("Start handle request of ECOMP pushUser"); + try { + if (user == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO); + log.debug("Recieved null for argument user"); + throw new PortalAPIException("Recieved null for argument user"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + final String modifierAttId = "jh0003"; + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + Either newASDCUser = EcompUserConverter.convertEcompUserToUser(user); + if (newASDCUser.isRight()) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO); + log.debug("Failed to create user {}", user); + throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); + } else if (newASDCUser.left().value() == null) { + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); + log.debug("Failed to create user {}", user); + throw new PortalAPIException("Failed to create user " + newASDCUser.right().value()); + } + + User convertedAsdcUser = newASDCUser.left().value(); + Either createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser); + + // ALREADY EXIST ResponseFormat + final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006"; + + if (createUserResponse.isRight()) { + if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) { + log.debug("Failed to create user {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to create user" + createUserResponse.right()); + } + log.debug("User already exist {}", user); + } + log.debug("User created {}", user); + } catch (Exception e) { + log.debug("Failed to create user {}", user, e); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to create user", e); + } + } + + /* + * (non-Javadoc) + * + * + * loginId - equals to userId + * + */ + @Override + public void editUser(String loginId, EcompUser user) throws PortalAPIException { + log.debug("Start handle request of ECOMP editUser"); + + try { + if (user == null) { + log.debug("Recieved null for argument user"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument user"); + } else if (loginId == null) { + log.debug("Recieved null for argument loginId"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument loginId"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) { + log.debug("loginId and user loginId not equal"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO); + throw new PortalAPIException("loginId not equals to the user loginId field"); + } else if (user.getLoginId() == null) { + user.setLoginId(loginId); + } + + Either asdcUser = EcompUserConverter.convertEcompUserToUser(user); + if (asdcUser.isRight()) { + log.debug("Failed to convert user"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO); + throw new PortalAPIException(asdcUser.right().value()); + } else if (asdcUser.left().value() == null) { + log.debug("NULL pointer returned from user converter"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to edit user"); + } + + Either updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value()); + + if (updateUserCredentialsResponse.isRight()) { + log.debug("Failed to updateUserCredentials"); + BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value()); + } + } catch (Exception e) { + log.debug("Failed to updateUserCredentials"); + throw new PortalAPIException("Failed to edit user", e); + } + + } + + @Override + public EcompUser getUser(String loginId) throws PortalAPIException { + log.debug("Start handle request of ECOMP getUser"); + + try { + + if (loginId == null) { + log.debug("Recieved null for argument loginId"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO); + throw new PortalAPIException("Recieved null for argument loginId"); + } + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + Either getUserResponse = userBusinessLogic.getUser(loginId, false); + + if (getUserResponse.isRight()) { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get User" + getUserResponse.right()); + } else { + if (getUserResponse.left().value() != null) { + Either ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); + if (ecompUser.isLeft() && ecompUser.left().value() != null) { + return ecompUser.left().value(); + } else { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException(ecompUser.right().value()); + } + } else { + log.debug("Failed to get User"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get User" + getUserResponse.right()); + } + } + } catch (Exception e) { + log.debug("Failed to get User"); + throw new PortalAPIException("Failed to get User", e); + } + } + + @Override + public List getUsers() throws PortalAPIException { + log.debug("Start handle request of ECOMP getUsers"); + + try { + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + final String modifierAttId = "jh0003"; + + Either, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null); + + if (getUsersResponse.isRight()) { + log.debug("Failed to get Users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); + } else { + if (getUsersResponse.left().value() != null) { + List ecompUserList = new LinkedList<>(); + for (User user : getUsersResponse.left().value()) { + Either ecompUser = EcompUserConverter.convertUserToEcompUser(user); + if (ecompUser.isRight()) { + log.debug("Failed to convert User {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); + continue; + } else if (ecompUser.left().value() == null) { + log.debug("Failed to convert User {}", user); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING); + continue; + } + ecompUserList.add(ecompUser.left().value()); + } + return ecompUserList; + } else { + log.debug("Failed to get users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users" + getUsersResponse.right()); + } + } + } catch (Exception e) { + log.debug("Failed to get users"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Users", e); + } + } + + @Override + public List getAvailableRoles() throws PortalAPIException { + log.debug("Start handle request of ECOMP getAvailableRoles"); + try { + List ecompRolesList = new LinkedList<>(); + for (Role role : Role.values()) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(new Long(role.ordinal())); + ecompRole.setName(role.name()); + ecompRolesList.add(ecompRole); + } + + if (ecompRolesList.isEmpty()) { + throw new PortalAPIException(); + } + + return ecompRolesList; + } catch (Exception e) { + log.debug("Failed to fetch roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO); + throw new PortalAPIException("Roles fetching failed", e); + } + + } + + /** + * The user role updated through this method only + */ + @Override + public void pushUserRole(String loginId, List roles) throws PortalAPIException { + log.debug("Start handle request of ECOMP pushUserRole"); + + final String modifierAttId = "jh0003"; + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + String updatedRole = null; + + if (roles == null) { + throw new PortalAPIException("Error: Recieved null for roles"); + } else if (roles.iterator().hasNext()) { + EcompRole ecompRole = roles.iterator().next(); + updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole); + log.debug("pushing role: {} to user: {}", updatedRole, loginId); + Either updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole); + if (updateUserRoleResponse.isRight()) { + log.debug("Error: Failed to update role"); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString()); + } + } else { + log.debug("Error: No roles in List"); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO); + //in this cases we want to deactivate the user + Either deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId); + if (deActivateUserResponse.isRight()) { + log.debug("Error: Failed to deactivate user {}",loginId); + BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO); + throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage()); + } + } + } + + @Override + public List getUserRoles(String loginId) throws PortalAPIException { + try { + log.debug("Start handle request of ECOMP getUserRoles"); + + UserBusinessLogic userBusinessLogic = getUserBusinessLogic(); + + Either getUserResponse = userBusinessLogic.getUser(loginId, false); + + if (getUserResponse.isRight()) { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); + } else { + if (getUserResponse.left().value() != null) { + Either ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value()); + if (ecompUser.isRight()) { + log.debug("Error: Failed to convert Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); + throw new PortalAPIException(ecompUser.right().value()); + } else if (ecompUser.left().value() == null) { + log.debug("Error: Failed to convert Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR); + throw new PortalAPIException(); + } + + return new LinkedList<>(ecompUser.left().value().getRoles()); + } else { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR); + throw new PortalAPIException("Failed to get Roles" + getUserResponse.right()); + } + } + } catch (Exception e) { + log.debug("Error: Failed to get Roles"); + BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO); + throw new PortalAPIException("Failed to get Roles", e); + } + } + + @Override + public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException { + // TODO Validation should be changed completely + final String USERNAME = request.getHeader("username"); + final String PASSWORD = request.getHeader("password"); + + if (USERNAME != null && PASSWORD != null) { + if (!USERNAME.equals("") && !PASSWORD.equals("")) { + log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD); + return true; + } + } + + log.debug("User authentication failed"); + return false; + } + + private UserBusinessLogic getUserBusinessLogic() { + ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext(); + UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); + return userBusinessLogic; + } + + /** * Gets and returns the userId for the logged-in user based on the request. * If any error occurs, the method should throw PortalApiException with an * appropriate message. The FW library will catch the exception and send an @@ -399,8 +394,8 @@ public class EcompIntImpl implements IPortalRestAPIService { * @throws PortalAPIException * If an unexpected error occurs while processing the request. */ - @Override - public String getUserId(HttpServletRequest request) throws PortalAPIException { - return request.getHeader(Constants.USER_ID_HEADER); - } + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + return request.getHeader(Constants.USER_ID_HEADER); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java index 93de8fed2c..b02a4a52cd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java @@ -20,30 +20,15 @@ package org.openecomp.sdc.be.ecomp.converters; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; -import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.*; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -52,341 +37,339 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.util.*; @org.springframework.stereotype.Component("asset-metadata-utils") public class AssetMetadataConverter { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - - @Autowired - private ComponentsUtils componentsUtils; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - /* - * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() - */ - public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { - if (componentList == null || componentList.isEmpty()) { - return Either.left(new LinkedList<>()); - } - List retResList = new LinkedList<>(); - - for (Component curr : componentList) { - Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - retResList.add(resMetaData.left().value()); - } - - return Either.left(retResList); - - } - - public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { - ComponentTypeEnum componentType = component.getComponentType(); - Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); - - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - else{ - return Either.left(resMetaData.left().value()); - } - - } - - private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { - - switch (componentType) { - - case RESOURCE: - - return generateResourceMeatdata(serverBaseURL, detailed, curr); - - case SERVICE: - - return generateServiceMetadata(serverBaseURL, detailed, curr); - - // For future US's that include product - /* - * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return - * Either.left(retResList); - */ - default: - - ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); - return Either.right(responseFormat); - } - } - - private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData; - metaData = createMetadaObject(detailed, curr.getComponentType()); - metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { - AssetMetadata metaData = null; - switch (type) { - case SERVICE: - if (!detailed) { - metaData = new ServiceAssetMetadata(); - } else { - metaData = new ServiceAssetDetailedMetadata(); - } - break; - case RESOURCE: - if (!detailed) { - metaData = new ResourceAssetMetadata(); - } else { - metaData = new ResourceAssetDetailedMetadata(); - } - break; - default: - break; - } - return metaData; - } - - private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); - - metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { - asset.setUuid(component.getUUID()); - asset.setInvariantUUID(component.getInvariantUUID()); - asset.setName(component.getName()); - asset.setVersion(component.getVersion()); - if (!detailed) { - asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); - } else { - String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); - asset.setToscaModelURL(toscaModelUrl); - } - - return asset; - } - - private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ - CategoryDefinition categoryDefinition = resource.getCategories().get(0); - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName()); - } - assetToPopulate.setResourceType(resource.getResourceType().name()); - assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); - - return (T) assetToPopulate; - } - - private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); - - if(service.getCategories() != null && !service.getCategories().isEmpty()){ - CategoryDefinition categoryDefinition = service.getCategories().get(0); - assetToPopulate.setCategory(categoryDefinition.getName()); - } - - assetToPopulate.setLifecycleState(service.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); - assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); - - return (T) assetToPopulate; - } - - private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { - - List componentInstances = resource.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = resource.getDeploymentArtifacts(); - assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); - assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); - assetToPopulate.setDescription(resource.getDescription()); - return Either.left(assetToPopulate); - } - - private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { - - List componentInstances = service.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = service.getDeploymentArtifacts(); - assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); - - return Either.left(assetToPopulate); - } - - private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(service, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private List populateAssetWithArtifacts(Component component, Map artifacts) { - List artifactMetaList = new LinkedList<>(); - if (artifacts != null) { - Collection artefactDefList = artifacts.values(); - - for (ArtifactDefinition artifactDefinition : artefactDefList) { - if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { - ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); - artifactMetaList.add(convertedArtifactMetadata); - } - } - } - return artifactMetaList.isEmpty() ? null : artifactMetaList; - } - - private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { - // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} - final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; - - // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} - final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; - - ArtifactMetadata metadata = new ArtifactMetadata(); - - metadata.setArtifactName(artifact.getArtifactName()); - metadata.setArtifactType(artifact.getArtifactType()); - - if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { - metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); - } else { - metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); - } - - metadata.setArtifactDescription(artifact.getDescription()); - metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); - metadata.setArtifactChecksum(artifact.getArtifactChecksum()); - metadata.setArtifactUUID(artifact.getArtifactUUID()); - metadata.setArtifactVersion(artifact.getArtifactVersion()); - metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); - metadata.setArtifactLabel(artifact.getArtifactLabel()); - metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); - return metadata; - } - - private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { - List retList = new LinkedList<>(); - Map> uuidDuplicatesMap = new HashMap<>(); - - for (ComponentInstance componentInstance : componentInstances) { - ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); - String componentUid = componentInstance.getComponentUid(); - String invariantUUID, resourceUUID; - - if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); - if (eitherResource.isRight()) { - log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); - return Either.right(eitherResource.right().value()); - } else { - final Resource resource = eitherResource.left().value(); - invariantUUID = resource.getInvariantUUID(); - resourceUUID = resource.getUUID(); - ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); - uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); - } - } else { - invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); - resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); - } - - metadata.setResourceInvariantUUID(invariantUUID); - metadata.setResourceUUID(resourceUUID); - metadata.setResourceInstanceName(componentInstance.getName()); - metadata.setResourceName(componentInstance.getComponentName()); - metadata.setResourceVersion(componentInstance.getComponentVersion()); - metadata.setResoucreType(componentInstance.getOriginType().getValue()); - - if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ - LinkedList artifactMetaList = new LinkedList<>(); - Collection values = componentInstance.getDeploymentArtifacts().values(); - for (ArtifactDefinition artifactDefinition : values) { - ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); - artifactMetaList.add(converted); - } - metadata.setArtifacts(artifactMetaList); - } - retList.add(metadata); - } - return Either.left(retList); - } - - // For future US to support Product - /* - * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); - * - * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); - * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); - * - * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); - * - * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = - * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition - * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); - * return retProdAsset; } } - */ + private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + /* + * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() + */ + public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { + if (componentList == null || componentList.isEmpty()) { + return Either.left(new LinkedList<>()); + } + List retResList = new LinkedList<>(); + + for (Component curr : componentList) { + Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + retResList.add(resMetaData.left().value()); + } + + return Either.left(retResList); + + } + + public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + ComponentTypeEnum componentType = component.getComponentType(); + Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); + + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + else{ + return Either.left(resMetaData.left().value()); + } + + } + + private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { + + switch (componentType) { + + case RESOURCE: + + return generateResourceMeatdata(serverBaseURL, detailed, curr); + + case SERVICE: + + return generateServiceMetadata(serverBaseURL, detailed, curr); + + // For future US's that include product + /* + * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return + * Either.left(retResList); + */ + default: + + ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); + return Either.right(responseFormat); + } + } + + private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData; + metaData = createMetadaObject(detailed, curr.getComponentType()); + metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { + AssetMetadata metaData = null; + switch (type) { + case SERVICE: + if (!detailed) { + metaData = new ServiceAssetMetadata(); + } else { + metaData = new ServiceAssetDetailedMetadata(); + } + break; + case RESOURCE: + if (!detailed) { + metaData = new ResourceAssetMetadata(); + } else { + metaData = new ResourceAssetDetailedMetadata(); + } + break; + default: + break; + } + return metaData; + } + + private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); + + metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { + asset.setUuid(component.getUUID()); + asset.setInvariantUUID(component.getInvariantUUID()); + asset.setName(component.getName()); + asset.setVersion(component.getVersion()); + if (!detailed) { + asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); + } else { + String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); + asset.setToscaModelURL(toscaModelUrl); + } + + return asset; + } + + private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); + if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + CategoryDefinition categoryDefinition = resource.getCategories().get(0); + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName()); + } + assetToPopulate.setResourceType(resource.getResourceType().name()); + assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); + + return (T) assetToPopulate; + } + + private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); + + if(service.getCategories() != null && !service.getCategories().isEmpty()){ + CategoryDefinition categoryDefinition = service.getCategories().get(0); + assetToPopulate.setCategory(categoryDefinition.getName()); + } + + assetToPopulate.setLifecycleState(service.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); + assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); + + return (T) assetToPopulate; + } + + private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { + + List componentInstances = resource.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); + assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); + assetToPopulate.setDescription(resource.getDescription()); + return Either.left(assetToPopulate); + } + + private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { + + List componentInstances = service.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = service.getDeploymentArtifacts(); + assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); + + return Either.left(assetToPopulate); + } + + private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(service, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private List populateAssetWithArtifacts(Component component, Map artifacts) { + List artifactMetaList = new LinkedList<>(); + if (artifacts != null) { + Collection artefactDefList = artifacts.values(); + + for (ArtifactDefinition artifactDefinition : artefactDefList) { + if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { + ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); + artifactMetaList.add(convertedArtifactMetadata); + } + } + } + return artifactMetaList.isEmpty() ? null : artifactMetaList; + } + + private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { + final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; + + final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + + ArtifactMetadata metadata = new ArtifactMetadata(); + + metadata.setArtifactName(artifact.getArtifactName()); + metadata.setArtifactType(artifact.getArtifactType()); + + if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { + metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); + } else { + metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); + } + + metadata.setArtifactDescription(artifact.getDescription()); + metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); + metadata.setArtifactChecksum(artifact.getArtifactChecksum()); + metadata.setArtifactUUID(artifact.getArtifactUUID()); + metadata.setArtifactVersion(artifact.getArtifactVersion()); + metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); + metadata.setArtifactLabel(artifact.getArtifactLabel()); + metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); + return metadata; + } + + private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { + List retList = new LinkedList<>(); + Map> uuidDuplicatesMap = new HashMap<>(); + + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); + String componentUid = componentInstance.getComponentUid(); + String invariantUUID, resourceUUID; + + if (!uuidDuplicatesMap.containsKey(componentUid)) { + Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); + if (eitherResource.isRight()) { + log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); + return Either.right(eitherResource.right().value()); + } else { + final Resource resource = eitherResource.left().value(); + invariantUUID = resource.getInvariantUUID(); + resourceUUID = resource.getUUID(); + ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); + uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); + } + } else { + invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); + resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); + } + + metadata.setResourceInvariantUUID(invariantUUID); + metadata.setResourceUUID(resourceUUID); + metadata.setResourceInstanceName(componentInstance.getName()); + metadata.setResourceName(componentInstance.getComponentName()); + metadata.setResourceVersion(componentInstance.getComponentVersion()); + metadata.setResoucreType(componentInstance.getOriginType().getValue()); + + if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ + LinkedList artifactMetaList = new LinkedList<>(); + Collection values = componentInstance.getDeploymentArtifacts().values(); + for (ArtifactDefinition artifactDefinition : values) { + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); + artifactMetaList.add(converted); + } + metadata.setArtifacts(artifactMetaList); + } + retList.add(metadata); + } + return Either.left(retList); + } + + // For future US to support Product + /* + * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); + * + * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); + * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); + * + * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); + * + * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = + * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition + * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); + * return retProdAsset; } } + */ } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java index 4ee3605703..6b0c85bb3e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java @@ -27,26 +27,26 @@ import org.slf4j.LoggerFactory; public final class EcompRoleConverter { - private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName()); - - private EcompRoleConverter() { - } - - // TODO Add Either or Exception in case of convertation failure - public static String convertEcompRoleToRole(EcompRole ecompRole) { - - log.debug("converting role"); - if (ecompRole == null) { - log.debug("recieved null for roles"); - return null; - } - - for (Role role : Role.values()) { - if (role.ordinal() == ecompRole.getId()) { - return role.name(); - } - } - log.debug("no roles converted"); - return null; - } + private static final Logger log = LoggerFactory.getLogger(EcompRoleConverter.class); + + private EcompRoleConverter() { + } + + // TODO Add Either or Exception in case of convertation failure + public static String convertEcompRoleToRole(EcompRole ecompRole) { + + log.debug("converting role"); + if (ecompRole == null) { + log.debug("recieved null for roles"); + return null; + } + + for (Role role : Role.values()) { + if (role.ordinal() == ecompRole.getId()) { + return role.name(); + } + } + log.debug("no roles converted"); + return null; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java index 19ef31feaf..590be72f1f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java @@ -20,91 +20,90 @@ package org.openecomp.sdc.be.ecomp.converters; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - +import fj.data.Either; import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; -import fj.data.Either; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; public final class EcompUserConverter { - private EcompUserConverter() { - } - - public static Either convertUserToEcompUser(User asdcUser) { - EcompUser convertedUser = new EcompUser(); - - if (asdcUser == null) { - return Either.right("User is null"); - } - - convertedUser.setFirstName(asdcUser.getFirstName()); - convertedUser.setLastName(asdcUser.getLastName()); - convertedUser.setLoginId(asdcUser.getUserId()); - convertedUser.setOrgUserId(asdcUser.getUserId()); - convertedUser.setEmail(asdcUser.getEmail()); - - if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) { - convertedUser.setActive(true); - } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) { - convertedUser.setActive(false); - } - - EcompRole convertedRole = new EcompRole(); - for (Role role : Role.values()) { - if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) { - convertedRole.setName(role.name()); - convertedRole.setId(new Long(role.ordinal())); - break; - } - } - - Set convertedRoleSet = new HashSet<>(); - convertedRoleSet.add(convertedRole); - convertedUser.setRoles(convertedRoleSet); - - return Either.left(convertedUser); - } - - public static Either convertEcompUserToUser(EcompUser ecompUser) { - User convertedUser = new User(); - - if (ecompUser == null) { - return Either.right("EcompUser is null"); - } - - convertedUser.setFirstName(ecompUser.getFirstName()); - convertedUser.setLastName(ecompUser.getLastName()); - - if (!ecompUser.getLoginId().isEmpty()) { - convertedUser.setUserId(ecompUser.getLoginId()); - } else { - convertedUser.setUserId(ecompUser.getOrgUserId()); - } - - convertedUser.setEmail(ecompUser.getEmail()); - - if (ecompUser.getRoles() != null) { - Iterator iter = ecompUser.getRoles().iterator(); - - if (iter.hasNext()) { - String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next()); - convertedUser.setRole(updatedRole); - } - } - - if (ecompUser.isActive()) { - convertedUser.setStatus(UserStatusEnum.ACTIVE); - } else { - convertedUser.setStatus(UserStatusEnum.INACTIVE); - } - - return Either.left(convertedUser); - } + private EcompUserConverter() { + } + + public static Either convertUserToEcompUser(User asdcUser) { + EcompUser convertedUser = new EcompUser(); + + if (asdcUser == null) { + return Either.right("User is null"); + } + + convertedUser.setFirstName(asdcUser.getFirstName()); + convertedUser.setLastName(asdcUser.getLastName()); + convertedUser.setLoginId(asdcUser.getUserId()); + convertedUser.setOrgUserId(asdcUser.getUserId()); + convertedUser.setEmail(asdcUser.getEmail()); + + if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) { + convertedUser.setActive(true); + } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) { + convertedUser.setActive(false); + } + + EcompRole convertedRole = new EcompRole(); + for (Role role : Role.values()) { + if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) { + convertedRole.setName(role.name()); + convertedRole.setId(new Long(role.ordinal())); + break; + } + } + + Set convertedRoleSet = new HashSet<>(); + convertedRoleSet.add(convertedRole); + convertedUser.setRoles(convertedRoleSet); + + return Either.left(convertedUser); + } + + public static Either convertEcompUserToUser(EcompUser ecompUser) { + User convertedUser = new User(); + + if (ecompUser == null) { + return Either.right("EcompUser is null"); + } + + convertedUser.setFirstName(ecompUser.getFirstName()); + convertedUser.setLastName(ecompUser.getLastName()); + + if (!ecompUser.getLoginId().isEmpty()) { + convertedUser.setUserId(ecompUser.getLoginId()); + } else { + convertedUser.setUserId(ecompUser.getOrgUserId()); + } + + convertedUser.setEmail(ecompUser.getEmail()); + + if (ecompUser.getRoles() != null) { + Iterator iter = ecompUser.getRoles().iterator(); + + if (iter.hasNext()) { + String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next()); + convertedUser.setRole(updatedRole); + } + } + + if (ecompUser.isActive()) { + convertedUser.setStatus(UserStatusEnum.ACTIVE); + } else { + convertedUser.setStatus(UserStatusEnum.INACTIVE); + } + + return Either.left(convertedUser); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java index 1408459470..70225c0dd2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java @@ -20,26 +20,15 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -56,16 +45,24 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; /** * This Servlet serves external users operations on artifacts. * @@ -78,740 +75,740 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ArtifactExternalServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class); + + private static String startLog = "Start handle request of "; + + /** + * Uploads an artifact to resource or service + * + * @param contenType + * @param checksum + * @param userId + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @param data + * @return + */ + @POST + @Path("/{assetType}/{uuid}/artifacts") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response uploadArtifact( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + String data) { + + init(log); - private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName()); - - private static String startLog = "Start handle request of "; + Wrapper responseWrapper = new Wrapper<>(); + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - /** - * Uploads an artifact to resource or service - * - * @param contenType - * @param checksum - * @param userId - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @param data - * @return - */ - @POST - @Path("/{assetType}/{uuid}/artifacts") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response uploadArtifact( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - String data) { - - init(log); - - Wrapper responseWrapper = new Wrapper<>(); - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - if (componentType == null) { - log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - if (responseWrapper.isEmpty() ) { - validateHttpCspUserIdHeader(userId, responseWrapper); - } - Response response = null; - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to upload artifact"); - responseWrapper.setInnerElement(uploadArtifactEither.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK)); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers); - } - } - if( response == null ){ - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - return response; - } catch (Exception e) { - final String message = "failed to upload artifact to a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams); - } - } + if (componentType == null) { + log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + if (responseWrapper.isEmpty() ) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + Response response = null; + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to upload artifact"); + responseWrapper.setInnerElement(uploadArtifactEither.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK)); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers); + } + } + if( response == null ){ + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + return response; + } catch (Exception e) { + final String message = "failed to upload artifact to a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams); + } + } - /** - * Uploads an artifact to resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @return - */ - @POST - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response uploadArtifactToInstance( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, - String data) { + /** + * Uploads an artifact to resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @return + */ + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response uploadArtifactToInstance( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, + String data) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - if (componentType == null) { - log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("uploadArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to upload artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - }catch (Exception e) { - final String message = "failed to upload artifact to a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + if (componentType == null) { + log.debug("uploadArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("uploadArtifact: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to upload artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + }catch (Exception e) { + final String message = "failed to upload artifact to a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * - * @param contenType - * @param checksum - * @param userId - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @param artifactUUID - * @param data - * @return - */ - @POST - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response updateArtifact( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - String data) { + /** + * + * @param contenType + * @param checksum + * @param userId + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @param artifactUUID + * @param data + * @return + */ + @POST + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response updateArtifact( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + String data) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("updateArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("updateArtifact: Missing USER_ID"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to update artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to update artifact on a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("updateArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("updateArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("updateArtifact: Missing USER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to update artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to update artifact on a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * updates an artifact on a resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @param artifactUUID - * @return - */ - @POST - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact") - public Response updateArtifactOnResourceInstance( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, - String data) { + /** + * updates an artifact on a resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @param artifactUUID + * @return + */ + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")}) + public Response updateArtifactOnResourceInstance( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum, + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName, + String data) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("updateArtifactOnResourceInstance: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to update artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to update artifact on resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("updateArtifactOnResourceInstance: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to update artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to update artifact on resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * deletes an artifact of a resource or service - * - * @param assetType - * @param uuid - * @param artifactUUID - * @return - */ - @DELETE - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class) - /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Asset not found") })*/ - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - public Response deleteArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { + /** + * deletes an artifact of a resource or service + * + * @param assetType + * @param uuid + * @param artifactUUID + * @return + */ + @DELETE + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class) + /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Asset not found") })*/ + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + public Response deleteArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("deleteArtifact: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to delete artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("deleteArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("deleteArtifact: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to delete artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * deletes an artifact of a resource instance - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @return - */ - @DELETE - @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), - @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), - @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), - @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), - @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) - public Response deleteArtifactOnResourceInstance( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { + /** + * deletes an artifact of a resource instance + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @return + */ + @DELETE + @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"), + @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"), + @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"), + @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"), + @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")}) + public Response deleteArtifactOnResourceInstance( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { - log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, - additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete)); - if (uploadArtifactEither.isRight()) { - log.debug("failed to delete artifact"); - responseFormat = uploadArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); - } - } - } catch (Exception e) { - final String message = "failed to delete an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) { + log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID, + additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE)); + if (uploadArtifactEither.isRight()) { + log.debug("failed to delete artifact"); + responseFormat = uploadArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value()); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers)); + } + } + } catch (Exception e) { + final String message = "failed to delete an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * downloads an artifact of a component (either a service or a resource) by artifactUUID - * - * @param assetType - * @param uuid - * @param artifactUUID - * @return - */ - @GET - @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) - public Response downloadComponentArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { + /** + * downloads an artifact of a component (either a service or a resource) by artifactUUID + * + * @param assetType + * @param uuid + * @param artifactUUID + * @return + */ + @GET + @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) + public Response downloadComponentArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams); - if (downloadComponentArtifactEither.isRight()) { - responseFormat = downloadComponentArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - byte[] value = downloadComponentArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); - } - } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource or service"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams); + if (downloadComponentArtifactEither.isRight()) { + responseFormat = downloadComponentArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + byte[] value = downloadComponentArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); + } + } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource or service"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } - /** - * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID - * - * @param assetType - * @param uuid - * @param resourceInstanceName - * @param artifactUUID - * @return - */ - @GET - @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(nickname = "downloadResourceInstanceArtifactByUUID",value = "Download resource instance artifact by artifact UUID", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) - public Response downloadResourceInstanceArtifact( - @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, - @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, - @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { + /** + * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID + * + * @param assetType + * @param uuid + * @param resourceInstanceName + * @param artifactUUID + * @return + */ + @GET + @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")}) + public Response downloadResourceInstanceArtifact( + @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID, + @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) { - Wrapper responseWrapper = new Wrapper<>(); - ResponseFormat responseFormat = null; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("{} {}", startLog, url); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - String componentTypeValue = componentType == null ? null : componentType.getValue(); - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); - if (componentType == null) { - log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { - log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } - try { - if (responseWrapper.isEmpty()) { - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); - if (downloadResourceArtifactEither.isRight()) { - responseFormat = downloadResourceArtifactEither.right().value(); - responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); - } else { - byte[] value = downloadResourceArtifactEither.left().value(); - InputStream is = new ByteArrayInputStream(value); - Map headers = new HashMap<>(); - headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); - } - } - } catch (Exception e) { - final String message = "failed to download an artifact of a resource instance"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); - } finally { - getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); - } - return responseWrapper.getInnerElement(); - } + Wrapper responseWrapper = new Wrapper<>(); + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("{} {}", startLog, url); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + String componentTypeValue = componentType == null ? null : componentType.getValue(); + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID); + if (componentType == null) { + log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) { + log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } + try { + if (responseWrapper.isEmpty()) { + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams); + if (downloadResourceArtifactEither.isRight()) { + responseFormat = downloadResourceArtifactEither.right().value(); + responseWrapper.setInnerElement(buildErrorResponse(responseFormat)); + } else { + byte[] value = downloadResourceArtifactEither.left().value(); + InputStream is = new ByteArrayInputStream(value); + Map headers = new HashMap<>(); + headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers)); + } + } + } catch (Exception e) { + final String message = "failed to download an artifact of a resource instance"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } finally { + getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams); + } + return responseWrapper.getInnerElement(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java index b9956063d6..27f82dfda3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java @@ -20,26 +20,9 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; @@ -61,14 +44,19 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * This Servlet serves external users for retrieving component metadata. @@ -83,311 +71,299 @@ import io.swagger.annotations.ApiResponses; @Singleton public class AssetsDataServlet extends AbstractValidationsServlet { - @Context - private HttpServletRequest request; - - private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName()); - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param category - * @param subCategory - * @param distributionStatus - * @param resourceType - * @return - */ - @GET - @Path("/{assetType}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getAssetListExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus, - @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) { - - Response response = null; - ResponseFormat responseFormat = null; - String query = request.getQueryString(); - String requestURI = request.getRequestURI().endsWith("/")? - removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST; - - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query); - - // Mandatory - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ServletContext context = request.getSession().getServletContext(); - ElementBusinessLogic elementLogic = getElementBL(context); - - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - Map filters = new EnumMap<>(FilterKeyEnum.class); - - if (category != null) { - filters.put(FilterKeyEnum.CATEGORY, category); - } - if (subCategory != null) { - filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory); - } - if (distributionStatus != null) { - filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus); - } - if (resourceType != null) { - ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType); - if (resourceTypeEnum == null) { - log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); - } - - Either, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query); - - if (assetTypeData.isRight()) { - log.debug("getAssetList: Asset Fetching Failed"); - responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } else { - log.debug("getAssetList: Asset Fetching Success"); - Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); - if (resMetadata.isRight()) { - log.debug("getAssetList: Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - response = buildOkResponse(responseFormat, result); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); - log.debug("getAssetList: Fetch list of assets failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @return - */ - @GET - @Path("/{assetType}/{uuid}/metadata") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getAssetSpecificMetadataByUuidExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { - - Response response = null; - ResponseFormat responseFormat = null; - AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA; - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - EnumMap additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - if (componentType == null) { - log.debug("getMetaData: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); - - // Mandatory - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ServletContext context = request.getSession().getServletContext(); - ElementBusinessLogic elementLogic = getElementBL(context); - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - - Either, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); - - if (assetTypeData.isRight()) { - log.debug("getAssetList: Asset Fetching Failed"); - responseFormat = assetTypeData.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - return buildErrorResponse(responseFormat); - } else { - log.debug("getAssetList: Asset Fetching Success"); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName()); - Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); - if (resMetadata.isRight()) { - log.debug("getAssetList: Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next()); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - - response = buildOkResponse(responseFormat, result); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); - log.debug("getAssetList: Fetch list of assets failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /** - * - * @param requestId - * @param instanceIdHeader - * @param accept - * @param authorization - * @param assetType - * @param uuid - * @return - */ - @GET - @Path("/{assetType}/{uuid}/toscaModel") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class), - @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) - public Response getToscaModelExternal( - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { - - String url = request.getRequestURI(); - log.debug("Start handle request of {} {}", request.getMethod(), url); - Response response = null; - ResponseFormat responseFormat = null; - ServletContext context = request.getSession().getServletContext(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL; - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - - if (componentType == null) { - log.debug("getToscaModel: assetType parameter {} is not valid", assetType); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); - - - if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { - log.debug("getToscaModel: Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return buildErrorResponse(responseFormat); - } - - try { - ComponentBusinessLogic componentBL = getComponentBL(componentType, context); - - Either, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam); - if (csarArtifact.isRight()) { - responseFormat = csarArtifact.right().value(); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - response = buildErrorResponse(responseFormat); - } else { - byte[] value = csarArtifact.left().value().getRight(); - InputStream is = new ByteArrayInputStream(value); - String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value); - Map headers = new HashMap<>(); - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft())); - headers.put(Constants.MD5_HEADER, contenetMD5); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - response = buildOkResponse(responseFormat, is, headers); - } - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model"); - log.debug("falied to get asset tosca model", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - response = buildErrorResponse(responseFormat); - getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); - return response; - } - } - - - private String removeDuplicateSlashSeparator(String requestUri) { - return requestUri.substring(0, requestUri.length()-1); - } + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(AssetsDataServlet.class); + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param category + * @param subCategory + * @param distributionStatus + * @param resourceType + * @return + */ + @GET + @Path("/{assetType}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getAssetListExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus, + @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) { + + Response response = null; + ResponseFormat responseFormat = null; + String query = request.getQueryString(); + String requestURI = request.getRequestURI().endsWith("/")? + removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST; + + EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query); + + // Mandatory + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ElementBusinessLogic elementLogic = getElementBL(context); + + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + Map filters = new EnumMap<>(FilterKeyEnum.class); + + if (category != null) { + filters.put(FilterKeyEnum.CATEGORY, category); + } + if (subCategory != null) { + filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory); + } + if (distributionStatus != null) { + filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus); + } + if (resourceType != null) { + ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType); + if (resourceTypeEnum == null) { + log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name()); + } + + Either, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query); + + if (assetTypeData.isRight()) { + log.debug("getAssetList: Asset Fetching Failed"); + responseFormat = assetTypeData.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } else { + log.debug("getAssetList: Asset Fetching Success"); + Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false); + if (resMetadata.isRight()) { + log.debug("getAssetList: Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + Object result = RepresentationUtils.toRepresentation(resMetadata.left().value()); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + response = buildOkResponse(responseFormat, result); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); + log.debug("getAssetList: Fetch list of assets failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @return + */ + @GET + @Path("/{assetType}/{uuid}/metadata") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getAssetSpecificMetadataByUuidExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { + + Response response = null; + ResponseFormat responseFormat = null; + AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + EnumMap additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); + + // Mandatory + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getAssetList: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ServletContext context = request.getSession().getServletContext(); + ElementBusinessLogic elementLogic = getElementBL(context); + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + + Either, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid); + + if (assetTypeData.isRight()) { + log.debug("getAssetList: Asset Fetching Failed"); + responseFormat = assetTypeData.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + return buildErrorResponse(responseFormat); + } else { + log.debug("getAssetList: Asset Fetching Success"); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName()); + Either, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true); + if (resMetadata.isRight()) { + log.debug("getAssetList: Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next()); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + + response = buildOkResponse(responseFormat, result); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets"); + log.debug("getAssetList: Fetch list of assets failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /** + * + * @param requestId + * @param instanceIdHeader + * @param accept + * @param authorization + * @param assetType + * @param uuid + * @return + */ + @GET + @Path("/{assetType}/{uuid}/toscaModel") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class), + @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")}) + public Response getToscaModelExternal( + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) { + + String url = request.getRequestURI(); + log.debug("Start handle request of {} {}", request.getMethod(), url); + Response response = null; + ResponseFormat responseFormat = null; + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL; + EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue()); + additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); + + if (instanceIdHeader == null || instanceIdHeader.isEmpty()) { + log.debug("getToscaModel: Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return buildErrorResponse(responseFormat); + } + + try { + ComponentBusinessLogic componentBL = getComponentBL(componentType, context); + + Either, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam); + if (csarArtifact.isRight()) { + responseFormat = csarArtifact.right().value(); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + response = buildErrorResponse(responseFormat); + } else { + byte[] value = csarArtifact.left().value().getRight(); + InputStream is = new ByteArrayInputStream(value); + String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value); + Map headers = new HashMap<>(); + headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft())); + headers.put(Constants.MD5_HEADER, contenetMD5); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + response = buildOkResponse(responseFormat, is, headers); + } + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model"); + log.debug("falied to get asset tosca model", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + response = buildErrorResponse(responseFormat); + getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam); + return response; + } + } + + + private String removeDuplicateSlashSeparator(String requestUri) { + return requestUri.substring(0, requestUri.length()-1); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java index 18422f53a1..0651291fc4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java @@ -20,30 +20,11 @@ package org.openecomp.sdc.be.externalapi.servlet; -import java.io.IOException; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.commons.lang3.StringUtils; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.elasticsearch.common.Strings; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -62,11 +43,7 @@ import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -82,508 +59,509 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "CRUD External Servlet", description = "This Servlet serves external users for creating assets and changing their lifecycle state") @Singleton public class CrudExternalServlet extends AbstractValidationsServlet { - - @Context - private HttpServletRequest request; - - private static Logger log = LoggerFactory.getLogger(CrudExternalServlet.class.getName()); - - /** - * Creates a new Resource - * - * @param assetType - * @param data - * @param userId - * @param instanceIdHeader - * @return - */ - @POST - @Path("/{assetType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class), - @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), - @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), - @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), - @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), - @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource") - public Response createResourceExternal( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, - String data) { - - init(log); - - Wrapper responseWrapper = new Wrapper<>(); - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - Resource resource = null; - User modifier = null; - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - ServletContext context = request.getSession().getServletContext(); - ResourceBusinessLogic resourceBL = getResourceBL(context); - try { - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - // Validate USER_ID Header - if (responseWrapper.isEmpty()) { - validateHttpCspUserIdHeader(userId, responseWrapper); - } - // Validate assetType - if (responseWrapper.isEmpty()) { - if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - //Validate resource type - if(responseWrapper.isEmpty()){ - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) parser.parse(data); - String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName()); - if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name")); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - // Convert the user json to a resource - if (responseWrapper.isEmpty()) { - modifier = new User(); - modifier.setUserId(userId); - Either eitherResource = getComponentsUtils() - .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, - null, ComponentTypeEnum.RESOURCE); - if( eitherResource.isRight() ){ - responseWrapper.setInnerElement(eitherResource.right().value()); - } - else{ - resource = eitherResource.left().value(); - } - - } - //validate name exist - if(responseWrapper.isEmpty()){ - if( Strings.isEmpty(resource.getName())){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); - - } - } - - if(responseWrapper.isEmpty()){ - resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root")); - resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName())); - resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), - resource.getSystemName())); - handleCategories(context, data, resource, responseWrapper); - } - // Create the resource in the dataModel - if (responseWrapper.isEmpty()) { - Either eitherCreateResponse = resourceBL.createResource(resource, null, - modifier, null, null); - if (eitherCreateResponse.isRight()) { - responseWrapper.setInnerElement(eitherCreateResponse.right().value()); - } else { - resource = eitherCreateResponse.left().value(); - } - } - Response response; - //Build Response and store it in the response Wrapper - if (responseWrapper.isEmpty()) { - response = buildCreatedResourceResponse(resource, context, responseWrapper); - } - else{ - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - return response; - - } catch (Exception e) { - final String message = "failed to create vfc monitoring template resource"; - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); - log.debug(message, e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - finally{ - prepareAdditionalAudit(resource, additionalParams); - - getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), - ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request, - additionalParams); - } - } - - /** - * Changing the lifecycle of an asset - * @param jsonChangeInfo The description - request body - * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources") - * @param uuid The uuid of the desired resource to be changed - * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST - * @param userId - * @return - */ - @POST - @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class), - @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), - @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), - @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), - @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), - @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), - @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), - @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"), - @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")}) - @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed") - public Response changeResourceStateExternal( - @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, - @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, - @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, - @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, - @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, - @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid, - @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType, - String jsonChangeInfo) { - - Response response = null; - EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); - - init(log); - - String requestURI = request.getRequestURI(); - String url = request.getMethod() + " " + requestURI; - log.debug("Start handle request of {}", url); - - //get the business logic - ServletContext context = request.getSession().getServletContext(); - LifecycleBusinessLogic businessLogic = getLifecycleBL(context); - - Wrapper responseWrapper = runValidations(assetType); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); - Component component = null; - Component responseObject = null; - User modifier = null; - - try{ - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); - } - - if (responseWrapper.isEmpty()) { - //get user - Either eitherGetUser = getUser(request, userId); - if (eitherGetUser.isRight()) { - ResponseFormat responseFormat = eitherGetUser.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - modifier = eitherGetUser.left().value(); - - //get the component id from the uuid - Either latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid); - if (latestVersion.isRight()) { - ResponseFormat responseFormat = latestVersion.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - component = latestVersion.left().value(); - String componentId = component.getUniqueId(); - - //validate the transition is valid - Either validateEnum = validateTransitionEnum(lifecycleTransition, modifier); - if (validateEnum.isRight()) { - ResponseFormat responseFormat = validateEnum.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); - - //create changeInfo - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); - try { - if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); - } - } - catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", jsonChangeInfo, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - - //execute business logic - Either actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); - if (actionResponse.isRight()) { - log.info("failed to change resource state"); - ResponseFormat responseFormat = actionResponse.right().value(); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } - - log.debug("change state successful !!!"); - responseObject = actionResponse.left().value(); - response = buildCreatedResourceResponse(responseObject, context, responseWrapper); - } else { - response = buildErrorResponse(responseWrapper.getInnerElement()); - } - - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); - log.debug("change lifecycle state failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - responseWrapper.setInnerElement(responseFormat); - return buildErrorResponse(responseFormat); - } finally{ - auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId); - } - } - - private void prepareAdditionalAudit(Resource resource, EnumMap additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY); - - if( resource != null ){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY); - } - } - - private Response buildCreatedResourceResponse(Component resource, ServletContext context, - Wrapper responseWrapper) throws IOException, JsonGenerationException, JsonMappingException { - ResponseFormat responseFormat; - Response response; - AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); - Either resMetadata = assetMetadataUtils - .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), - true); - if (resMetadata.isRight()) { - log.debug("Asset conversion Failed"); - responseFormat = resMetadata.right().value(); - responseWrapper.setInnerElement(responseFormat); - response = buildErrorResponse(responseFormat); - }else{ - final AssetMetadata assetData = resMetadata.left().value(); - assetData.setToscaModelURL(null); - - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); - Object representation = RepresentationUtils.toRepresentation(assetData); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); - } - return response; - } - - private void handleCategories(ServletContext context, String data, Resource resource, - Wrapper responseWrapper) { - try { - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) parser.parse(data); - String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue()); - String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue()); - if (Strings.isEmpty(category)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - else if (Strings.isEmpty(subcategory)) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); - } - if (responseWrapper.isEmpty()) { - ElementBusinessLogic elementLogic = getElementBL(context); - // get All Categories - Either, ActionStatus> allResourceCategories = elementLogic - .getAllResourceCategories(); - // Error fetching categories - if (allResourceCategories.isRight()) { - responseWrapper.setInnerElement( - getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); - } else { - addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); - } - } - } catch (Exception e) { - log.debug("Exception occured in addCategories: {}", e.getMessage(), e); - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - private void addCategories(Resource resource, String category, String subcategory, - Either, ActionStatus> allResourceCategories, - Wrapper responseWrapper) { - Optional optionalCategory = - // Stream of all the categories - allResourceCategories.left().value().stream() - // filter in only relevant category - .filter(e -> e.getName().equals(category)) - // get the result - .findAny(); - if (!optionalCategory.isPresent()) { - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } else { - CategoryDefinition categoryDefinition = optionalCategory.get(); - - List subCaregories = - // Stream of all sub-categories of the relevant - // category - categoryDefinition.getSubcategories().stream() - // filter in only relevant sub-category - .filter(e -> e.getName().equals(subcategory)) - // get the result - .collect(Collectors.toList()); - - if( subCaregories.isEmpty() ){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( - ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue())); - } - else{ - categoryDefinition.setSubcategories(subCaregories); - resource.setCategories(Arrays.asList(categoryDefinition)); - } - - } - } - - - - - private void auditChnageLifecycleAction(EnumMap additionalParams, - Wrapper responseWrapper, ComponentTypeEnum componentType, Component component, - Component responseObject, User modifier, String userId) { - if (modifier!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId); - } - - if (component!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); - } - - if (responseObject!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name()); - } else { - if (component!=null){ - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID()); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name()); - } else { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,""); - } - } - - getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), - componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request, - additionalParams); - } - - private Wrapper runValidations(final String assetType) { - Wrapper responseWrapper = new Wrapper<>(); - - // Validate X-ECOMP-InstanceID Header - if (responseWrapper.isEmpty()) { - String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); - validateXECOMPInstanceIDHeader(instanceId,responseWrapper); - } - // Validate USER_ID Header - if (responseWrapper.isEmpty()) { - validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); - } - // Validate assetType - if (responseWrapper.isEmpty()) { - if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){ - responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - } - - return responseWrapper; - } - - private Either validateTransitionEnum(final String lifecycleTransition, User user) { - LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; - try { - transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); - } catch (IllegalArgumentException e) { - log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(error); - } - return Either.left(transitionEnum); - } + + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(CrudExternalServlet.class); + + /** + * Creates a new Resource + * + * @param assetType + * @param data + * @param userId + * @param instanceIdHeader + * @return + */ + @POST + @Path("/{assetType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"), + @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"), + @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource")}) + public Response createResourceExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, + String data) { + + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + Resource resource = null; + User modifier = null; + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + ServletContext context = request.getSession().getServletContext(); + ResourceBusinessLogic resourceBL = getResourceBL(context); + try { + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + //Validate resource type + if(responseWrapper.isEmpty()){ + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName()); + if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name")); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + // Convert the user json to a resource + if (responseWrapper.isEmpty()) { + modifier = new User(); + modifier.setUserId(userId); + Either eitherResource = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, + null, ComponentTypeEnum.RESOURCE); + if( eitherResource.isRight() ){ + responseWrapper.setInnerElement(eitherResource.right().value()); + } + else{ + resource = eitherResource.left().value(); + } + + } + //validate name exist + if(responseWrapper.isEmpty()){ + if( Strings.isEmpty(resource.getName())){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue())); + + } + } + + if(responseWrapper.isEmpty()){ + resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root")); + resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName())); + resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), + resource.getSystemName())); + handleCategories(context, data, resource, responseWrapper); + } + // Create the resource in the dataModel + if (responseWrapper.isEmpty()) { + Either eitherCreateResponse = resourceBL.createResource(resource, null, + modifier, null, null); + if (eitherCreateResponse.isRight()) { + responseWrapper.setInnerElement(eitherCreateResponse.right().value()); + } else { + resource = eitherCreateResponse.left().value(); + } + } + Response response; + //Build Response and store it in the response Wrapper + if (responseWrapper.isEmpty()) { + response = buildCreatedResourceResponse(resource, context, responseWrapper); + } + else{ + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + return response; + + } catch (Exception e) { + final String message = "failed to create vfc monitoring template resource"; + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message); + log.debug(message, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + finally{ + prepareAdditionalAudit(resource, additionalParams); + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request, + additionalParams); + } + } + + /** + * Changing the lifecycle of an asset + * @param jsonChangeInfo The description - request body + * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources") + * @param uuid The uuid of the desired resource to be changed + * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST + * @param userId + * @return + */ + @POST + @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"), + @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")}) + @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")}) + public Response changeResourceStateExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid, + @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType, + String jsonChangeInfo) { + + Response response = null; + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + + init(log); + + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + log.debug("Start handle request of {}", url); + + //get the business logic + ServletContext context = request.getSession().getServletContext(); + LifecycleBusinessLogic businessLogic = getLifecycleBL(context); + + Wrapper responseWrapper = runValidations(assetType); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType); + Component component = null; + Component responseObject = null; + User modifier = null; + + try{ + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + + if (responseWrapper.isEmpty()) { + //get user + Either eitherGetUser = getUser(request, userId); + if (eitherGetUser.isRight()) { + ResponseFormat responseFormat = eitherGetUser.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + modifier = eitherGetUser.left().value(); + + //get the component id from the uuid + Either latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid); + if (latestVersion.isRight()) { + ResponseFormat responseFormat = latestVersion.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + component = latestVersion.left().value(); + String componentId = component.getUniqueId(); + + //validate the transition is valid + Either validateEnum = validateTransitionEnum(lifecycleTransition, modifier); + if (validateEnum.isRight()) { + ResponseFormat responseFormat = validateEnum.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); + + //create changeInfo + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); + try { + if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); + } + } + catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", jsonChangeInfo, e); + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + //execute business logic + Either actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true); + if (actionResponse.isRight()) { + log.info("failed to change resource state"); + ResponseFormat responseFormat = actionResponse.right().value(); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } + + log.debug("change state successful !!!"); + responseObject = actionResponse.left().value(); + response = buildCreatedResourceResponse(responseObject, context, responseWrapper); + } else { + response = buildErrorResponse(responseWrapper.getInnerElement()); + } + + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); + log.debug("change lifecycle state failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + responseWrapper.setInnerElement(responseFormat); + return buildErrorResponse(responseFormat); + } finally{ + auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId); + } + } + + private void prepareAdditionalAudit(Resource resource, EnumMap additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY); + + if( resource != null ){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY); + } + } + + private Response buildCreatedResourceResponse(Component resource, ServletContext context, + Wrapper responseWrapper) throws IOException { + ResponseFormat responseFormat; + Response response; + AssetMetadataConverter assetMetadataUtils = getAssetUtils(context); + Either resMetadata = assetMetadataUtils + .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), + true); + if (resMetadata.isRight()) { + log.debug("Asset conversion Failed"); + responseFormat = resMetadata.right().value(); + responseWrapper.setInnerElement(responseFormat); + response = buildErrorResponse(responseFormat); + }else{ + final AssetMetadata assetData = resMetadata.left().value(); + assetData.setToscaModelURL(null); + + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED)); + Object representation = RepresentationUtils.toRepresentation(assetData); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); + } + return response; + } + + private void handleCategories(ServletContext context, String data, Resource resource, + Wrapper responseWrapper) { + try { + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) parser.parse(data); + String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue()); + String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue()); + if (Strings.isEmpty(category)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else if (Strings.isEmpty(subcategory)) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_MISSING_SUBCATEGORY)); + } + if (responseWrapper.isEmpty()) { + ElementBusinessLogic elementLogic = getElementBL(context); + // get All Categories + Either, ActionStatus> allResourceCategories = elementLogic + .getAllResourceCategories(); + // Error fetching categories + if (allResourceCategories.isRight()) { + responseWrapper.setInnerElement( + getComponentsUtils().getResponseFormat(allResourceCategories.right().value())); + } else { + addCategories(resource, category, subcategory, allResourceCategories, responseWrapper); + } + } + } catch (Exception e) { + log.debug("Exception occured in addCategories: {}", e.getMessage(), e); + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + private void addCategories(Resource resource, String category, String subcategory, + Either, ActionStatus> allResourceCategories, + Wrapper responseWrapper) { + Optional optionalCategory = + // Stream of all the categories + allResourceCategories.left().value().stream() + // filter in only relevant category + .filter(e -> e.getName().equals(category)) + // get the result + .findAny(); + if (!optionalCategory.isPresent()) { + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } else { + CategoryDefinition categoryDefinition = optionalCategory.get(); + + List subCaregories = + // Stream of all sub-categories of the relevant + // category + categoryDefinition.getSubcategories().stream() + // filter in only relevant sub-category + .filter(e -> e.getName().equals(subcategory)) + // get the result + .collect(Collectors.toList()); + + if( subCaregories.isEmpty() ){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat( + ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue())); + } + else{ + categoryDefinition.setSubcategories(subCaregories); + resource.setCategories(Arrays.asList(categoryDefinition)); + } + + } + } + + + + + private void auditChnageLifecycleAction(EnumMap additionalParams, + Wrapper responseWrapper, ComponentTypeEnum componentType, Component component, + Component responseObject, User modifier, String userId) { + if (modifier!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId); + } + + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, ""); + } + + if (responseObject!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name()); + } else { + if (component!=null){ + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID()); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name()); + } else { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,""); + } + } + + getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), + componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request, + additionalParams); + } + + private Wrapper runValidations(final String assetType) { + Wrapper responseWrapper = new Wrapper<>(); + + // Validate X-ECOMP-InstanceID Header + if (responseWrapper.isEmpty()) { + String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); + validateXECOMPInstanceIDHeader(instanceId,responseWrapper); + } + // Validate USER_ID Header + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper); + } + // Validate assetType + if (responseWrapper.isEmpty()) { + if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){ + responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); + } + } + + return responseWrapper; + } + + private Either validateTransitionEnum(final String lifecycleTransition, User user) { + LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; + try { + transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); + } catch (IllegalArgumentException e) { + log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(error); + } + return Either.left(transitionEnum); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java new file mode 100644 index 0000000000..7e48890c7d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java @@ -0,0 +1,214 @@ +package org.openecomp.sdc.be.externalapi.servlet; + +import fj.data.Either; +import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; +import java.util.Map; + + +@Path("/v1/catalog") +@Controller +public class ExternalRefsServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(ExternalRefsServlet.class); + + private ExternalRefsBusinessLogic businessLogic; + + public ExternalRefsServlet(ExternalRefsBusinessLogic businessLogic, ComponentsUtils componentsUtils){ + this.businessLogic = businessLogic; + this.componentsUtils = componentsUtils; + } + + @GET + @Path("/{assetType}/{uuid}/version/{version}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}") + @Produces(MediaType.APPLICATION_JSON) + public Response getComponentInstanceExternalRef( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("version") String version, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) { + + log.debug("GET component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, componentInstanceName, objectType); + if (refsResult.isLeft()){ + return this.buildOkResponse(refsResult.left().value()); + } else { + return this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, componentInstanceName, objectType, ""); + } + } + + @GET + @Path("/{assetType}/{uuid}/version/{version}/externalReferences/{objectType}") + @Produces(MediaType.APPLICATION_JSON) + public Map> getAssetExternalRefByObjectType( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("version") String version, + @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) { + + log.debug("GET asset external references {} {} {}", assetType, uuid, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + throw new WebApplicationException(r); + } + + Either>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, objectType); + if (refsResult.isLeft()){ + return refsResult.left().value(); + } else { + throw new WebApplicationException(this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, "", objectType, "")); + } + } + + @POST + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response addComponentInstanceExternalRef( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, ExternalRefDTO ref, @HeaderParam("USER_ID") String userId) { + + log.debug("POST component instance external interfaces {} {} {} {} {}", assetType, uuid, componentInstanceName, objectType, ref); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either addResult = this.businessLogic.addExternalReference(uuid, componentInstanceName, objectType, ref); + if (addResult.isLeft()) { + return Response.status(Response.Status.CREATED) + .entity(ref) + .build(); + } else { + return this.buildExtRefErrorResponse(addResult.right().value(), uuid, "", componentInstanceName, objectType, ref.getReferenceUUID()); + } + + } + + @DELETE + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{reference}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteComponentInstanceReference( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, + @PathParam("reference") String reference, @HeaderParam("USER_ID") String userId) { + + log.debug("DELETE component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + Either deleteStatus = this.businessLogic.deleteExternalReference(uuid, componentInstanceName, objectType, reference); + if (deleteStatus.isLeft()){ + return this.buildOkResponse(new ExternalRefDTO(reference)); + } else { + return this.buildExtRefErrorResponse(deleteStatus.right().value(), uuid, "", componentInstanceName, objectType, reference); + } + } + + @PUT + @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{oldRefValue}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response updateComponentInstanceReference( + @Context final HttpServletRequest request, + @PathParam("assetType") String assetType, + @PathParam("uuid") String uuid, + @PathParam("componentInstanceName") String componentInstanceName, + @PathParam("objectType") String objectType, + @PathParam("oldRefValue") String oldRefValue, + ExternalRefDTO newRefValueDTO, @HeaderParam("USER_ID") String userId) { + + log.debug("PUT component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType); + + Response r = authorizeAndValidateRequest(request, userId); + if (r != null){ + return r; + } + + String newRefValue = newRefValueDTO.getReferenceUUID(); + Either updateResult = this.businessLogic.updateExternalReference(uuid, componentInstanceName, objectType, oldRefValue, newRefValue); + if (updateResult.isLeft()){ + return this.buildOkResponse(new ExternalRefDTO(newRefValue)); + } else { + return this.buildExtRefErrorResponse(updateResult.right().value(), uuid, "", componentInstanceName, objectType, oldRefValue); + } + + } + + private Response authorizeAndValidateRequest(final HttpServletRequest request, String userId) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + Wrapper userWrapper = new Wrapper<>(); + + //Validate X-ECOMP_INSTANCE_ID_HEADER + if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null || request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER).isEmpty()){ + return this.buildExtRefErrorResponse(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID, "", "", "", "", ""); + } + + String method = request.getMethod(); + if (responseWrapper.isEmpty() && !"GET".equals(method)) { + validateUserExist(responseWrapper, userWrapper, userId); + validateUserRole(responseWrapper, userWrapper.getInnerElement()); + } + + return responseWrapper.getInnerElement(); + } + + private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType, String ref){ + switch (status) { + case RESOURCE_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid)); + case COMPONENT_VERSION_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid, version)); + case COMPONENT_INSTANCE_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, componentInstanceName, uuid)); + case EXT_REF_ALREADY_EXIST: + return Response.status(Response.Status.OK) + .entity(new ExternalRefDTO(ref)) + .build(); + case EXT_REF_NOT_FOUND: + return buildErrorResponse(componentsUtils.getResponseFormat(status, objectType + "/" + ref)); + case MISSING_X_ECOMP_INSTANCE_ID: + return buildErrorResponse(componentsUtils.getResponseFormat(status)); + default: + return this.buildGeneralErrorResponse(); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java new file mode 100644 index 0000000000..3f1bf18edb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java @@ -0,0 +1,167 @@ +package org.openecomp.sdc.be.externalapi.servlet; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.servlets.AbstractValidationsServlet; +import org.openecomp.sdc.be.servlets.RepresentationUtils; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.EnumMap; + +/** + * Created by chaya on 10/17/2017. + */ +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service") +@Singleton +public class ServiceActivationServlet extends AbstractValidationsServlet { + + @Context + private HttpServletRequest request; + + private static final Logger log = LoggerFactory.getLogger(ServiceActivationServlet.class); + + /** + * Activates a service on a specific environment + * + * @param serviceUUID + * @param opEnvId + * @param userId + * @param instanceIdHeader + * @return + */ + @POST + @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "activate a service", httpMethod = "POST", notes = "Activates a service") + @ApiResponses(value = { + @ApiResponse(code = 202, message = "ECOMP component is authenticated and required service may be distributed"), + @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"), + @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"), + @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"), + @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"), + @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"), + @ApiResponse(code = 500, message = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"), + @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"), + @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"), + @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"), + @ApiResponse(code = 409, message = "Service state is invalid for this action"), + @ApiResponse(code = 502, message = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")}) + public Response activateServiceExternal( + @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType, + @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId, + @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader, + @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept, + @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, + @ApiParam(value = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID, + @ApiParam(value = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId, + String data) { + + init(log); + + ResponseFormat responseFormat = null; + String requestURI = request.getRequestURI(); + String url = request.getMethod() + " " + requestURI; + EnumMap additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + log.debug("Start handle request of {}", url); + + ServletContext context = request.getSession().getServletContext(); + try { + + Wrapper responseWrapper = validateRequestHeaders(instanceIdHeader, userId); + + if (responseWrapper.isEmpty()) { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + ServiceBusinessLogic businessLogic = getServiceBL(context); + ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data); + Either distResponse = businessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata); + + if (distResponse.isRight()) { + log.debug("failed to activate service distribution"); + responseFormat = distResponse.right().value(); + return buildErrorResponse(responseFormat); + } + String distributionId = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId)); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED); + return buildOkResponse(responseFormat, result); + } else { + log.debug("request instanceId/userId header validation failed"); + responseFormat = responseWrapper.getInnerElement(); + return buildErrorResponse(responseFormat); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); + log.debug("activate distribution failed with exception", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } finally { + getComponentsUtils().auditExternalActivateService(responseFormat, ComponentTypeEnum.SERVICE.name(), request, additionalParams); + } + } + + private Wrapper validateRequestHeaders(String instanceIdHeader, String userId) { + Wrapper responseWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper); + } + if (responseWrapper.isEmpty()) { + validateHttpCspUserIdHeader(userId, responseWrapper); + } + return responseWrapper; + } + + private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.readValue(data, ServiceDistributionReqInfo.class); + } catch (IOException e) { + log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e); + return new ServiceDistributionReqInfo(null); + } + } + + @Override + protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { + ResponseFormat responseFormat; + if( StringUtils.isEmpty(header)){ + log.debug("MissingUSER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + responseWrapper.setInnerElement(responseFormat); + } + } +} + + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java index 15ebceaa5d..e41d8d7548 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java @@ -21,104 +21,104 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ArtifactMetadata { - private String artifactName; - private String artifactType; - private String artifactURL; - private String artifactDescription; - private Integer artifactTimeout; - private String artifactChecksum; - private String artifactUUID; - private String artifactVersion; - private String generatedFromUUID; - private String artifactLabel; - private String artifactGroupType; - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactType() { - return artifactType; - } - - public void setArtifactType(String artifactType) { - this.artifactType = artifactType; - } - - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - public String getArtifactDescription() { - return artifactDescription; - } - - public void setArtifactDescription(String artifactDescription) { - this.artifactDescription = artifactDescription; - } - - public Integer getArtifactTimeout() { - return artifactTimeout; - } - - public void setArtifactTimeout(Integer artifactTimeout) { - this.artifactTimeout = artifactTimeout; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public void setArtifactChecksum(String artifactChecksum) { - this.artifactChecksum = artifactChecksum; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getGeneratedFromUUID() { - return generatedFromUUID; - } - - public void setGeneratedFromUUID(String generatedFromUUID) { - this.generatedFromUUID = generatedFromUUID; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public void setArtifactLabel(String artifactLabel) { - this.artifactLabel = artifactLabel; - } - - public String getArtifactGroupType() { - return artifactGroupType; - } - - public void setArtifactGroupType(String artifactGroupType) { - this.artifactGroupType = artifactGroupType; - } + private String artifactName; + private String artifactType; + private String artifactURL; + private String artifactDescription; + private Integer artifactTimeout; + private String artifactChecksum; + private String artifactUUID; + private String artifactVersion; + private String generatedFromUUID; + private String artifactLabel; + private String artifactGroupType; + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public Integer getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(Integer artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java index cb14f76aff..b12411a7b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java @@ -21,109 +21,109 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public abstract class AssetMetadata implements IAssetMetadata { - private String uuid; - private String invariantUUID; - private String name; - private String version; - private String toscaModelURL; + private String uuid; + private String invariantUUID; + private String name; + private String version; + private String toscaModelURL; - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid() - */ - @Override - public String getUuid() { - return uuid; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid() + */ + @Override + public String getUuid() { + return uuid; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String) - */ - @Override - public void setUuid(String uuid) { - this.uuid = uuid; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String) + */ + @Override + public void setUuid(String uuid) { + this.uuid = uuid; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID() - */ - @Override - public String getInvariantUUID() { - return invariantUUID; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID() + */ + @Override + public String getInvariantUUID() { + return invariantUUID; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String) - */ - @Override - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String) + */ + @Override + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName() - */ - @Override - public String getName() { - return name; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName() + */ + @Override + public String getName() { + return name; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String) - */ - @Override - public void setName(String name) { - this.name = name; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String) + */ + @Override + public void setName(String name) { + this.name = name; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion() - */ - @Override - public String getVersion() { - return version; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion() + */ + @Override + public String getVersion() { + return version; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String) - */ - @Override - public void setVersion(String version) { - this.version = version; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String) + */ + @Override + public void setVersion(String version) { + this.version = version; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL() - */ - @Override - public String getToscaModelURL() { - return toscaModelURL; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL() + */ + @Override + public String getToscaModelURL() { + return toscaModelURL; + } - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String) - */ - @Override - public void setToscaModelURL(String toscaModelURL) { - this.toscaModelURL = toscaModelURL; - } + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String) + */ + @Override + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java index f95a8e9684..319e16a294 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java @@ -22,24 +22,24 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public interface IAssetMetadata { - String getUuid(); + String getUuid(); - void setUuid(String uuid); + void setUuid(String uuid); - String getInvariantUUID(); + String getInvariantUUID(); - void setInvariantUUID(String invariantUUID); + void setInvariantUUID(String invariantUUID); - String getName(); + String getName(); - void setName(String name); + void setName(String name); - String getVersion(); + String getVersion(); - void setVersion(String version); + void setVersion(String version); - String getToscaModelURL(); + String getToscaModelURL(); - void setToscaModelURL(String toscaModelURL); + void setToscaModelURL(String toscaModelURL); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java index d2d9c2c902..40b78c12d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java @@ -23,50 +23,50 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ProductAssetMetadata extends AssetMetadata { - private String lifecycleState; - private String lastUpdaterUserId; - private boolean isActive; - private List contacts; - private List productGroupings; + private String lifecycleState; + private String lastUpdaterUserId; + private boolean isActive; + private List contacts; + private List productGroupings; - public String getLifecycleState() { - return lifecycleState; - } + public String getLifecycleState() { + return lifecycleState; + } - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } - public boolean isActive() { - return isActive; - } + public boolean isActive() { + return isActive; + } - public void setActive(boolean isActive) { - this.isActive = isActive; - } + public void setActive(boolean isActive) { + this.isActive = isActive; + } - public List getContacts() { - return contacts; - } + public List getContacts() { + return contacts; + } - public void setContacts(List contacts) { - this.contacts = contacts; - } + public void setContacts(List contacts) { + this.contacts = contacts; + } - public List getProductGroupings() { - return productGroupings; - } + public List getProductGroupings() { + return productGroupings; + } - public void setProductGroupings(List productGroupings) { - this.productGroupings = productGroupings; - } + public void setProductGroupings(List productGroupings) { + this.productGroupings = productGroupings; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java index 047f9d6a2c..7d666df703 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java @@ -21,37 +21,37 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ProductCategoryGroupMetadata { - private String category; - private String subCategory; - private String group; - - public ProductCategoryGroupMetadata(String category, String subCategory, String group) { - this.category = category; - this.subCategory = subCategory; - this.group = group; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubCategory() { - return subCategory; - } - - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } - - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } + private String category; + private String subCategory; + private String group; + + public ProductCategoryGroupMetadata(String category, String subCategory, String group) { + this.category = category; + this.subCategory = subCategory; + this.group = group; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java index 0952feea05..eb15e077de 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java @@ -24,50 +24,50 @@ import java.util.List; public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata { - private String lastUpdaterFullName; - private String toscaResourceName; - private List resources; - private List artifacts; - private String description; + private String lastUpdaterFullName; + private String toscaResourceName; + private List resources; + private List artifacts; + private String description; - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } - public String getToscaResourceName() { - return toscaResourceName; - } + public String getToscaResourceName() { + return toscaResourceName; + } - public void setToscaResourceName(String toscaResourceName) { - this.toscaResourceName = toscaResourceName; - } + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } - public List getResources() { - return resources; - } + public List getResources() { + return resources; + } - public void setResources(List resources) { - this.resources = resources; - } + public void setResources(List resources) { + this.resources = resources; + } - public List getArtifacts() { - return artifacts; - } + public List getArtifacts() { + return artifacts; + } - public void setArtifacts(List artifactMetaList) { - this.artifacts = artifactMetaList; - } + public void setArtifacts(List artifactMetaList) { + this.artifacts = artifactMetaList; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } - public void setDescription(String description) { - this.description = description; - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java index 2b75facc6c..455e125ffc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java @@ -21,49 +21,49 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ResourceAssetMetadata extends AssetMetadata { - private String category; - private String subCategory; - private String resourceType; - private String lifecycleState; - private String lastUpdaterUserId; + private String category; + private String subCategory; + private String resourceType; + private String lifecycleState; + private String lastUpdaterUserId; - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public void setCategory(String category) { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } - public String getSubCategory() { - return subCategory; - } + public String getSubCategory() { + return subCategory; + } - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } - public String getResourceType() { - return resourceType; - } + public String getResourceType() { + return resourceType; + } - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } - public String getLifecycleState() { - return lifecycleState; - } + public String getLifecycleState() { + return lifecycleState; + } - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java index a53422f311..1023f82249 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java @@ -23,67 +23,67 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ResourceInstanceMetadata { - private String resourceInstanceName; - private String resourceName; - private String resourceInvariantUUID; - private String resourceVersion; - private String resoucreType; - private String resourceUUID; - private List artifacts; - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(String resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public String getResoucreType() { - return resoucreType; - } - - public void setResoucreType(String resoucreType) { - this.resoucreType = resoucreType; - } - - public String getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(String resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } + private String resourceInstanceName; + private String resourceName; + private String resourceInvariantUUID; + private String resourceVersion; + private String resoucreType; + private String resourceUUID; + private List artifacts; + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resoucreType; + } + + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java index edd88b495d..e677fdc190 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java @@ -23,31 +23,31 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; import java.util.List; public class ServiceAssetDetailedMetadata extends ServiceAssetMetadata { - private String lastUpdaterFullName; - private List resources; - private List artifacts; + private String lastUpdaterFullName; + private List resources; + private List artifacts; - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } - public List getResources() { - return resources; - } + public List getResources() { + return resources; + } - public void setResources(List resources) { - this.resources = resources; - } + public void setResources(List resources) { + this.resources = resources; + } - public List getArtifacts() { - return artifacts; - } + public List getArtifacts() { + return artifacts; + } - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java index 094f973553..6e5ac8426c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java @@ -21,40 +21,40 @@ package org.openecomp.sdc.be.externalapi.servlet.representation; public class ServiceAssetMetadata extends AssetMetadata { - private String category; - private String lifecycleState; - private String lastUpdaterUserId; - private String distributionStatus; - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getLifecycleState() { - return lifecycleState; - } - - public void setLifecycleState(String lifecycleState) { - this.lifecycleState = lifecycleState; - } - - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } - - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } - - public String getDistributionStatus() { - return distributionStatus; - } - - public void setDistributionStatus(String distributionStatus) { - this.distributionStatus = distributionStatus; - } + private String category; + private String lifecycleState; + private String lastUpdaterUserId; + private String distributionStatus; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getDistributionStatus() { + return distributionStatus; + } + + public void setDistributionStatus(String distributionStatus) { + this.distributionStatus = distributionStatus; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java new file mode 100644 index 0000000000..5557c7a609 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.externalapi.servlet.representation; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionReqInfo { + + private String workloadContext; + + public ServiceDistributionReqInfo() { + } + public ServiceDistributionReqInfo(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java new file mode 100644 index 0000000000..3fa54c3654 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.be.externalapi.servlet.representation; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionRespInfo { + + private String distributionId; + + public ServiceDistributionRespInfo() { + } + + public ServiceDistributionRespInfo(String distributionId) { + this.distributionId = distributionId; + } + + public String getDistributionId() { + return distributionId; + } + + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java index de95790f4e..841cd3225d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java @@ -20,27 +20,15 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.StringTokenizer; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ConsumerDefinition; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.openecomp.sdc.security.Passwords; @@ -48,178 +36,186 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.StringTokenizer; @Priority(10) public class BasicAuthenticationFilter implements ContainerRequestFilter { - @Context - private HttpServletRequest sr; - - protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - private String realm = "ASDC"; - - private static Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER); - if (authHeader != null) { - StringTokenizer st = new StringTokenizer(authHeader); - if (st.hasMoreTokens()) { - String basic = st.nextToken(); - - if (basic.equalsIgnoreCase("Basic")) { - try { - String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); - log.debug("Credentials: {}" , credentials); - checkUserCredentiles(requestContext, credentials); - } catch (UnsupportedEncodingException e) { - log.error("Authentication Filter Failed Couldn't retrieve authentication", e); - authInvalidHeaderError(requestContext); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - } - - } else { - log.error("Authentication Filter Failed no autharization header"); - authRequiredError(requestContext); - } - } - - private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) { - int p = credentials.indexOf(":"); - if (p != -1) { - String _username = credentials.substring(0, p).trim(); - String _password = credentials.substring(p + 1).trim(); - - ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic(); - if (consumerBL == null) { - log.error("Authentication Filter Failed to get consumerBL."); - requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); - } else { - Either result = consumerBL.getConsumer(_username); - validatePassword(requestContext, _username, _password, result); - } - } else { - log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); - authInvalidHeaderError(requestContext); - - } - } - - private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either result) { - if (result.isRight()) { - Integer status = result.right().value().getStatus(); - if (status == Status.NOT_FOUND.getStatusCode()) { - log.error("Authentication Filter Failed Couldn't find user"); - authUserNotFoundError(requestContext, _username); - } else { - log.error("Authentication Filter Failed to get consumerBL."); - requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); - } - } else { - ConsumerDefinition consumerCredentials = result.left().value(); - if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) { - log.error("Authentication Filter Failed invalide password"); - authInvalidePasswordError(requestContext, _username); - } else { - authSuccesessful(requestContext, _username); - } - } - } - - private void authSuccesessful(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm); - } - - private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authInvalidHeaderError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER); - requestContext.abortWith(buildErrorResponse(responseFormat, false)); - } - - private void authRequiredError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Authentication Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED); - requestContext.abortWith(buildErrorResponse(responseFormat, true)); - } - - private ComponentsUtils getComponentsUtils() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - private ConsumerBusinessLogic getConsumerBusinessLogic() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class); - return consumerBusinessLogic; - } - - public enum AuthStatus { - AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS - } - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) { - ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus()); - if (addWwwAuthenticationHeader) { - responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\""); - } - Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - return response; - } + @Context + private HttpServletRequest sr; + + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + private String realm = "ASDC"; + + private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + + String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER); + if (authHeader != null) { + StringTokenizer st = new StringTokenizer(authHeader); + if (st.hasMoreTokens()) { + String basic = st.nextToken(); + + if (basic.equalsIgnoreCase("Basic")) { + try { + String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); + log.debug("Credentials: {}" , credentials); + checkUserCredentiles(requestContext, credentials); + } catch (UnsupportedEncodingException e) { + log.error("Authentication Filter Failed Couldn't retrieve authentication", e); + authInvalidHeaderError(requestContext); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + } + + } else { + log.error("Authentication Filter Failed no autharization header"); + authRequiredError(requestContext); + } + } + + private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) { + int p = credentials.indexOf(":"); + if (p != -1) { + String _username = credentials.substring(0, p).trim(); + String _password = credentials.substring(p + 1).trim(); + + ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic(); + if (consumerBL == null) { + log.error("Authentication Filter Failed to get consumerBL."); + requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); + } else { + Either result = consumerBL.getConsumer(_username); + validatePassword(requestContext, _username, _password, result); + } + } else { + log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication."); + authInvalidHeaderError(requestContext); + + } + } + + private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either result) { + if (result.isRight()) { + Integer status = result.right().value().getStatus(); + if (status == Status.NOT_FOUND.getStatusCode()) { + log.error("Authentication Filter Failed Couldn't find user"); + authUserNotFoundError(requestContext, _username); + } else { + log.error("Authentication Filter Failed to get consumerBL."); + requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); + } + } else { + ConsumerDefinition consumerCredentials = result.left().value(); + if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) { + log.error("Authentication Filter Failed invalide password"); + authInvalidePasswordError(requestContext, _username); + } else { + authSuccesessful(requestContext, _username); + } + } + } + + private void authSuccesessful(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm); + } + + private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authInvalidHeaderError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER); + requestContext.abortWith(buildErrorResponse(responseFormat, false)); + } + + private void authRequiredError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Authentication Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED); + requestContext.abortWith(buildErrorResponse(responseFormat, true)); + } + + private ComponentsUtils getComponentsUtils() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); + return componentsUtils; + } + + private ConsumerBusinessLogic getConsumerBusinessLogic() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class); + return consumerBusinessLogic; + } + + public enum AuthStatus { + AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS + } + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) { + ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus()); + if (addWwwAuthenticationHeader) { + responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\""); + } + Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java index d24743534c..60409b3ee0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java @@ -20,20 +20,7 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.util.UUID; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - +import com.google.gson.GsonBuilder; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -50,171 +37,180 @@ import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.GsonBuilder; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.util.UUID; @Provider @Priority(1) public class BeServletFilter implements ContainerRequestFilter, ContainerResponseFilter { - @Context - private HttpServletRequest sr; - - private static Logger log = LoggerFactory.getLogger(BeServletFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - try { - - MDC.clear(); - - // In case of 405 response code, this function is not entered, then - // we'll process - // the MDC fields and UUID during the response - ThreadLocalsHolder.setMdcProcessed(true); - - // Timing HTTP request - ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); - - String uuid = processMdcFields(requestContext); - - ThreadLocalsHolder.setUuid(uuid); - - inHttpRequest(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during request filter: {} ", e); - } - } - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - try { - // Formatting the response in case of 405 - if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); - responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); - } - - if (ThreadLocalsHolder.isMdcProcessed()) { - // filter() was executed during request - this is the regular - // flow - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); - Long startTime = ThreadLocalsHolder.getRequestStartTime(); - if (startTime != null) { - long endTime = System.currentTimeMillis(); - MDC.put("timer", Long.toString(endTime - startTime)); - } - } else { - // this is the 405 response code case - // we have no MDC fields since filter() wasn't executed during - // request - String uuid = processMdcFields(requestContext); - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid); - } - - outHttpResponse(responseContext); - - log.debug("Close transaction from filter"); - TitanDao titanDao = getTitanDao(); - if ( titanDao != null ){ - if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){ - titanDao.commit(); - log.debug("Doing commit from filter"); - }else{ - titanDao.rollback(); - log.debug("Doing rollback from filter"); - } - } - // Cleaning up - MDC.clear(); - ThreadLocalsHolder.cleanup(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during response filter: {} ", e); - } - } - - private String processMdcFields(ContainerRequestContext requestContext) { - // UserId for logging - String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); - MDC.put("userId", userId); - - String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER); - MDC.put("serviceInstanceID", serviceInstanceID); - - MDC.put("remoteAddr", sr.getRemoteAddr()); - MDC.put("localAddr", sr.getLocalAddr()); - - // UUID - String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER); - if (uuid == null) { - // Generate the UUID - uuid = UUID.randomUUID().toString(); - - // Add to MDC for logging - MDC.put("uuid", uuid); - - // This log message should already be with the UUID - uuidGeneration(uuid); - - } else { - // According to Ella, in case this header exists, we don't have to - // perform any validations - // since it's not our responsibilty, so we log the UUID just as it - // was received. - MDC.put("uuid", uuid); - } - return uuid; - } - - private ComponentsUtils getComponentsUtils() { - ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(ComponentsUtils.class); - } - private TitanDao getTitanDao() { - ServletContext context = this.sr.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(TitanDao.class); - } - // Extracted for purpose of clear method name, for logback %M parameter - private void inHttpRequest() { - if (isInfoLog()) { - log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } else { - log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void outHttpResponse(ContainerResponseContext responseContext) { - if (isInfoLog()) { - log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } else { - log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } - } - - private boolean isInfoLog() { - boolean logRequest = true; - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - String requestURI = sr.getRequestURI(); - if (requestURI != null && configuration.getUnLoggedUrls() != null) { - logRequest = !configuration.getUnLoggedUrls().contains(requestURI); - } - - return logRequest; - } - - // Extracted for purpose of clear method name, for logback %M parameter - private void uuidGeneration(String uuid) { - log.info("No requestID provided -> Generated UUID {}", uuid); - } + @Context + private HttpServletRequest sr; + + private static final Logger log = LoggerFactory.getLogger(BeServletFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + try { + + MDC.clear(); + + // In case of 405 response code, this function is not entered, then + // we'll process + // the MDC fields and UUID during the response + ThreadLocalsHolder.setMdcProcessed(true); + + // Timing HTTP request + ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); + + String uuid = processMdcFields(requestContext); + + ThreadLocalsHolder.setUuid(uuid); + + inHttpRequest(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during request filter: {} ", e); + } + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + try { + // Formatting the response in case of 405 + if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); + responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); + } + + if (ThreadLocalsHolder.isMdcProcessed()) { + // filter() was executed during request - this is the regular + // flow + responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); + Long startTime = ThreadLocalsHolder.getRequestStartTime(); + if (startTime != null) { + long endTime = System.currentTimeMillis(); + MDC.put("timer", Long.toString(endTime - startTime)); + } + } else { + // this is the 405 response code case + // we have no MDC fields since filter() wasn't executed during + // request + String uuid = processMdcFields(requestContext); + responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid); + } + + outHttpResponse(responseContext); + + log.debug("Close transaction from filter"); + TitanDao titanDao = getTitanDao(); + if ( titanDao != null ){ + if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){ + titanDao.commit(); + log.debug("Doing commit from filter"); + }else{ + titanDao.rollback(); + log.debug("Doing rollback from filter"); + } + } + // Cleaning up + MDC.clear(); + ThreadLocalsHolder.cleanup(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during response filter: {} ", e); + } + } + + private String processMdcFields(ContainerRequestContext requestContext) { + // UserId for logging + String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); + MDC.put("userId", userId); + + String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER); + MDC.put("serviceInstanceID", serviceInstanceID); + + MDC.put("remoteAddr", sr.getRemoteAddr()); + MDC.put("localAddr", sr.getLocalAddr()); + + // UUID + String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER); + if (uuid == null) { + // Generate the UUID + uuid = UUID.randomUUID().toString(); + + // Add to MDC for logging + MDC.put("uuid", uuid); + + // This log message should already be with the UUID + uuidGeneration(uuid); + + } else { + // According to Ella, in case this header exists, we don't have to + // perform any validations + // since it's not our responsibilty, so we log the UUID just as it + // was received. + MDC.put("uuid", uuid); + } + return uuid; + } + + private ComponentsUtils getComponentsUtils() { + ServletContext context = this.sr.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentsUtils.class); + } + private TitanDao getTitanDao() { + ServletContext context = this.sr.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(TitanDao.class); + } + // Extracted for purpose of clear method name, for logback %M parameter + private void inHttpRequest() { + if (isInfoLog()) { + log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); + } else { + log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); + } + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void outHttpResponse(ContainerResponseContext responseContext) { + if (isInfoLog()) { + log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); + } else { + log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); + } + } + + private boolean isInfoLog() { + boolean logRequest = true; + Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); + String requestURI = sr.getRequestURI(); + if (requestURI != null && configuration.getUnLoggedUrls() != null) { + logRequest = !configuration.getUnLoggedUrls().contains(requestURI); + } + + return logRequest; + } + + // Extracted for purpose of clear method name, for logback %M parameter + private void uuidGeneration(String uuid) { + log.info("No requestID provided -> Generated UUID {}", uuid); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java index c572e2e552..b80ee4c324 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java @@ -20,21 +20,9 @@ package org.openecomp.sdc.be.filters; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.Priority; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.Response.Status; - -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -46,77 +34,87 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Priority; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; @Priority(11) public class ComponentsAvailabilityFilter implements ContainerRequestFilter { - @Context - protected HttpServletRequest sr; - protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); - private static Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class.getName()); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - String requestUrl = requestContext.getUriInfo().getPath(); - if (!requestUrl.equals("healthCheck")) { - List beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext()); - ActionStatus status = getAggregateBeStatus(beHealthCheckInfos); - - if (!status.equals(ActionStatus.OK)) { - log.error("Components Availability Filter Failed - ES/Cassandra is DOWN"); - availabilityError(requestContext); - } - } - - } - - protected ActionStatus getAggregateBeStatus(List beHealthCheckInfos) { - ActionStatus status = ActionStatus.OK; - for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { - if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { - status = ActionStatus.GENERAL_ERROR; - break; - } - } - return status; - } - - protected List getBeHealthCheckInfos(ServletContext servletContext) { - - List healthCheckInfos = new ArrayList(); - HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); - healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan - return healthCheckInfos; - } - - protected ComponentsUtils getComponentsUtils() { - ServletContext context = sr.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - protected void availabilityError(ContainerRequestContext requestContext) { - ComponentsUtils componentUtils = getComponentsUtils(); - if (componentUtils == null) { - log.error("Components Availability Filter Failed to get component utils."); - requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus()); - Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build(); - requestContext.abortWith(response); - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } + @Context + protected HttpServletRequest sr; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + private static final Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class); + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + + String requestUrl = requestContext.getUriInfo().getPath(); + if (!requestUrl.equals("healthCheck")) { + List beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext()); + ActionStatus status = getAggregateBeStatus(beHealthCheckInfos); + + if (!status.equals(ActionStatus.OK)) { + log.error("Components Availability Filter Failed - ES/Cassandra is DOWN"); + availabilityError(requestContext); + } + } + + } + + protected ActionStatus getAggregateBeStatus(List beHealthCheckInfos) { + ActionStatus status = ActionStatus.OK; + for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) { + if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) { + status = ActionStatus.GENERAL_ERROR; + break; + } + } + return status; + } + + protected List getBeHealthCheckInfos(ServletContext servletContext) { + + List healthCheckInfos = new ArrayList(); + HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); + healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan + return healthCheckInfos; + } + + protected ComponentsUtils getComponentsUtils() { + ServletContext context = sr.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); + return componentsUtils; + } + + protected void availabilityError(ContainerRequestContext requestContext) { + ComponentsUtils componentUtils = getComponentsUtils(); + if (componentUtils == null) { + log.error("Components Availability Filter Failed to get component utils."); + requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus()); + Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build(); + requestContext.abortWith(response); + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index 910521c8dc..566daec5e7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -20,23 +20,24 @@ package org.openecomp.sdc.be.impl; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; - -import org.codehaus.jackson.Version; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.JsonDeserializer; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.module.SimpleModule; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditConsumerEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditResourceEventFactoryMananger; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.auditing.impl.distribution.AuditDistribDownloadEventFactory; +import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAccessEventFactory; +import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAdminEventFactory; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -46,7 +47,6 @@ import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ConsumerDefinition; @@ -56,12 +56,14 @@ import org.openecomp.sdc.be.model.PolicyTypeDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.tosca.ToscaError; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; @@ -71,1451 +73,1370 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component("componentUtils") public class ComponentsUtils { - @javax.annotation.Resource - private IAuditingManager auditingManager; - - private ResponseFormatManager responseFormatManager; - - private static Logger log = LoggerFactory.getLogger(ComponentsUtils.class.getName()); - - @PostConstruct - public void Init() { - this.responseFormatManager = ResponseFormatManager.getInstance(); - } - - public IAuditingManager getAuditingManager() { - return auditingManager; - } - - public void setAuditingManager(IAuditingManager auditingManager) { - this.auditingManager = auditingManager; - } - - public Either convertJsonToObject(String data, User user, Class clazz, AuditingActionEnum actionEnum) { - if (data == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - try { - T obj = parseJsonToObject(data, clazz); - return Either.left(obj); - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - } - - public static T parseJsonToObject(String data, Class clazz) { - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - log.trace("convert json to object. json=\n{}", data); - T resource = gson.fromJson(data, clazz); - return resource; - } - - public Either convertJsonToObjectUsingObjectMapper(String data, User user, Class clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { - T component = null; - ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - try { - log.trace("convert json to object. json=\n{}", data); - - final SimpleModule module = new SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static version")); - JsonDeserializer desrializer = new PropertyConstraintJacksonDeserialiser(); - addDeserializer(module, PropertyConstraint.class, desrializer); - // - mapper.registerModule(module); - - component = mapper.readValue(data, clazz); - if (component == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); - return Either.right(responseFormat); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); - return Either.right(responseFormat); - } - return Either.left(component); - } - - public void addDeserializer(SimpleModule module, Class clazz, final JsonDeserializer deserializer) { - module.addDeserializer(clazz, deserializer); - } - - // Error response - - public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) { - return responseFormatManager.getResponseFormat(actionStatus, params); - } - - public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) { - return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params); - } - - /** - * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he - * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields. - * - * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service. - * - * @param actionStatus - * @param resource - * @return - */ - public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) { - if (resource == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case COMPONENT_VERSION_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion()); - break; - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName()); - break; - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); - break; - case COMPONENT_IN_USE: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) { - if (resourceName == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) { - if (capabilityType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case CAPABILITY_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) { - if (obj == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat = null; - - switch (actionStatus) { - case MISSING_CAPABILITY_TYPE: - if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)){ - List list = (List)obj; - if ( list.get(0) instanceof RequirementDefinition ) { - responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object - return responseFormat; - } - } - log.debug("UNKNOWN TYPE : expecting obj as a non empty List"); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - /** - * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he - * received. It's caller's responisibility to fill the passed resource object with needed fields. - * - * @param actionStatus - * @param user - * @return - */ - public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) { - if (user == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat requestErrorWrapper; - switch (actionStatus) { - case INVALID_USER_ID: - requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); - break; - case INVALID_EMAIL_ADDRESS: - requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail()); - break; - case INVALID_ROLE: - requestErrorWrapper = getResponseFormat(actionStatus, user.getRole()); - break; - case USER_NOT_FOUND: - case USER_ALREADY_EXIST: - case USER_INACTIVE: - case USER_HAS_ACTIVE_ELEMENTS: - requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); - break; - default: - requestErrorWrapper = getResponseFormat(actionStatus); - break; - } - return requestErrorWrapper; - } - - public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) { - User user = new User(); - user.setUserId(userId); - return getResponseFormatByUser(actionStatus, user); - } - - public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName); - break; - case DISTRIBUTION_ENVIRONMENT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName); - break; - case DISTRIBUTION_ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_NOT_FOUND: - case ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) { - ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("audit before sending response"); - auditResource(responseFormat, user, null, "", "", actionEnum, null); - return responseFormat; - } - - public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { - ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); - log.debug("audit before sending response"); - auditComponentAdmin(responseFormat, user, null, "", "", actionEnum, typeEnum); - return responseFormat; - } - - public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String prevState, String prevVersion, AuditingActionEnum actionEnum, EnumMap additionalParams) { - if (actionEnum != null) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - updateUserFields(modifier, auditingFields); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState); - if (resource != null) { - // fields that are filled during creation and might still be - // empty - String resourceCurrVersion = (resource.getVersion() != null) ? resource.getVersion() : ""; - String resourceCurrState = (resource.getLifecycleState() != null) ? resource.getLifecycleState().name() : ""; - String uuid = (resource.getUUID() != null) ? resource.getUUID() : ""; - String invariantUUID = (resource.getInvariantUUID() != null) ? resource.getInvariantUUID() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID); - - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // In those specific cases we want some specific fields from - // resource object - switch (actionEnum) { - case IMPORT_RESOURCE: - if (resource != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, resource.getToscaResourceName()); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, ""); - } - break; - default: - break; - } - - // This is to add/overwrite anything set in this function if some - // params were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - } - - private void updateUserFields(User modifier, EnumMap auditingFields) { - if (modifier != null) { - String firstName = modifier.getFirstName(); - String lastName = modifier.getLastName(); - if (firstName != null || lastName != null) {// to prevent "null - // null" names - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - } - - public void auditDistributionDownload(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // This is to add/overwrite anything set in this function if some params - // were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap additionalParams) { - log.trace("Inside auditing for audit action {}", actionEnum); - String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); - String requestURI = request.getRequestURI(); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - int status = 0; - String message = ""; - if(responseFormat != null){ - status = responseFormat.getStatus(); - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - if(!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)){ - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - } - } - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); - } - - public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); - } - - public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); - } - - public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); - additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); - auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); - } - - public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - updateUserFields(modifier, auditingFields); - // String componentTypeStr = (componentTypeEnum != null ? - // componentTypeEnum.getValue() : null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName); - getAuditingManager().auditEvent(auditingFields); - } - - public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) { - - return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE); - } - - public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) { - - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - if (storageResponse == null) { - return responseEnum; - } - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; - break; - case PARENT_RESOURCE_NOT_FOUND: - responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND; - break; - case MULTIPLE_PARENT_RESOURCE_FOUND: - responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND; - break; - case NOT_FOUND: - if (ComponentTypeEnum.RESOURCE == type) { - responseEnum = ActionStatus.RESOURCE_NOT_FOUND; - } else if (ComponentTypeEnum.PRODUCT == type) { - responseEnum = ActionStatus.PRODUCT_NOT_FOUND; - } else { - responseEnum = ActionStatus.SERVICE_NOT_FOUND; - } - break; - case FAILED_TO_LOCK_ELEMENT: - responseEnum = ActionStatus.COMPONENT_IN_USE; - break; - case ARTIFACT_NOT_FOUND: - responseEnum = ActionStatus.ARTIFACT_NOT_FOUND; - break; - case DISTR_ENVIRONMENT_NOT_AVAILABLE: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE; - break; - case DISTR_ENVIRONMENT_NOT_FOUND: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND; - break; - case DISTR_ENVIRONMENT_SENT_IS_INVALID: - responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID; - break; - case DISTR_ARTIFACT_NOT_FOUND: - responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND; - break; - case INVALID_TYPE: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case INVALID_VALUE: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case CSAR_NOT_FOUND: - responseEnum = ActionStatus.CSAR_NOT_FOUND; - break; - case PROPERTY_NAME_ALREADY_EXISTS: - responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY; - break; - case CATEGORY_NOT_FOUND: - responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; - break; - case INVALID_PROPERTY: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromToscaError(ToscaError toscaError) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - if (toscaError == null) { - return responseEnum; - } - switch (toscaError) {// TODO match errors - case NODE_TYPE_CAPABILITY_ERROR: - case NOT_SUPPORTED_TOSCA_TYPE: - case NODE_TYPE_REQUIREMENT_ERROR: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case INVALID_ID: - responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; - break; - case INVALID_PROPERTY: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; - break; - case NOT_FOUND: - if (isRelation) { - responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND; - } else { - responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; - } - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_INSTANCE_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - break; - default: - responseFormat = getResponseFormat(actionStatus, serviceName); - break; - } - return responseFormat; - } - - public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) { - ResponseFormat responseFormat; - - switch (actionStatus) { - case RESOURCE_INSTANCE_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus, resourceInstanceName); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case INVALID_ID: - responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; - break; - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case MATCH_NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; - break; - case NOT_FOUND: - responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type) { - auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type, null); - } - - public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type, EnumMap additionalParams) { - if (actionEnum != null) { - log.trace("Inside auditing for audit action {}", actionEnum.name()); - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - updateUserFields(modifier, auditingFields); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, type.getValue().replace(" ", "")); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState); - if (component != null) { - // fields that are filled during creation and might still be - // empty - String resourceCurrVersion = component.getVersion(); - String resourceCurrState = (component.getLifecycleState() != null) ? component.getLifecycleState().name() : ""; - String resourceUuid = (component.getUUID() != null) ? component.getUUID() : ""; - String invariantUUID = (component.getInvariantUUID() != null) ? component.getInvariantUUID() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resourceUuid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, ""); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, ""); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - // This is meant to overwrite anything set in this function if some - // params were passed from above, - // for example resourceName of resource import - if (additionalParams != null) { - auditingFields.putAll(additionalParams); - } - - getAuditingManager().auditEvent(auditingFields); - } - } - - public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState, - String topicName, String distributionId, String description, String status) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); - - // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, - // environmentName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditAuthEvent(AuditingActionEnum actionEnum, String url, String user, String authStatus, String realm) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, url); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, user); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, authStatus); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, realm); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId); - ThreadLocalsHolder.setUuid(distributionId); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) { - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion); - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - StringBuilder ecompUser = new StringBuilder(); - if (consumer != null) { - if (consumer.getConsumerName() != null && !consumer.getConsumerName().trim().isEmpty()) { - ecompUser.append(consumer.getConsumerName()); - } - if (consumer.getConsumerSalt() != null && !consumer.getConsumerSalt().trim().isEmpty()) { - if (ecompUser.length() > 0) { - ecompUser.append(","); - } - ecompUser.append(consumer.getConsumerSalt()); - } - if (consumer.getConsumerPassword() != null && !consumer.getConsumerPassword().trim().isEmpty()) { - if (ecompUser.length() > 0) { - ecompUser.append(","); - } - ecompUser.append(consumer.getConsumerPassword()); - } - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, ecompUser.toString()); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, ""); - } - if (userBefore != null) { - String userBeforeUserId = (userBefore.getUserId() != null) ? userBefore.getUserId() : ""; - String userBeforFirstName = (userBefore.getFirstName() != null) ? ", " + userBefore.getFirstName() + " " : ""; - String userBeforLastName = (userBefore.getLastName() != null) ? userBefore.getLastName() : ""; - String userBeforEmail = (userBefore.getEmail() != null) ? ", " + userBefore.getEmail() : ""; - String userBeforRloe = (userBefore.getRole() != null) ? ", " + userBefore.getRole() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, userBeforeUserId + userBeforFirstName + userBeforLastName + userBeforEmail + userBeforRloe); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, ""); - } - if (userAfter != null) { - String userAfterUserId = (userAfter.getUserId() != null) ? userAfter.getUserId() : ""; - String userAfterFirstName = (userAfter.getFirstName() != null) ? ", " + userAfter.getFirstName() + " " : ""; - String userAfterLastName = (userAfter.getLastName() != null) ? userAfter.getLastName() : ""; - String userAfterEmail = (userAfter.getEmail() != null) ? ", " + userAfter.getEmail() : ""; - String userAfterRloe = (userAfter.getRole() != null) ? ", " + userAfter.getRole() : ""; - - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, userAfterUserId + userAfterFirstName + userAfterLastName + userAfterEmail + userAfterRloe); - } else { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, ""); - } - - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')'); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { - - EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); - if (modifier != null) { - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); - } - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details); - int status = responseFormat.getStatus(); - String message = ""; - - if (responseFormat.getMessageId() != null) { - message = responseFormat.getMessageId() + ": "; - } - message += responseFormat.getFormattedMessage(); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); - getAuditingManager().auditEvent(auditingFields); - } - - public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) { - if (component == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case COMPONENT_VERSION_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion()); - break; - case RESOURCE_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - case COMPONENT_IN_USE: - responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId()); - break; - case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: - responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } - - public Either validateStringNotEmpty(User user, Component component, String value, ActionStatus badResult, AuditingActionEnum actionEnum) { - if ((value == null) || (value.trim().isEmpty())) { - log.info(badResult.name()); - ResponseFormat errorResponse = getResponseFormat(badResult); - if (actionEnum != null) { - log.debug("audit before sending response"); - auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component)); - } - return Either.right(errorResponse); - } - return Either.left(true); - } - - public Boolean validateStringNotEmpty(String value) { - if ((value == null) || (value.trim().isEmpty())) { - return false; - } - return true; - } - - private ComponentTypeEnum getComponentType(Component component) { - if (component instanceof Service) { - return ComponentTypeEnum.SERVICE; - } // else if(component instanceof Resource){ - return null; - } - - public Either validateStringMatchesPattern(User user, Component component, String value, Pattern pattern, ActionStatus badResult, AuditingActionEnum actionEnum) { - if (!pattern.matcher(value).matches()) { - log.error(badResult.name()); - ResponseFormat errorResponse = getResponseFormat(badResult); - if (actionEnum != null) { - log.debug("audit before sending response"); - auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component)); - } - return Either.right(errorResponse); - } - return Either.left(true); - } - - /** - * - * " Error: Missing Mandatory Informational %s1 %s2 : %s3 " where %s1 - "resource"/"service" %s2 - "artifact"/ "artifacts" %s3 - Comma separated list of missing informational artifact types - * - * @param resource - * @param componentMissingMandatoryArtifacts - * @param value - * @return - */ - public ResponseFormat getResponseFormatByMissingArtifacts(ComponentTypeEnum componentType, Map artifacts) { - - String artifactTitle = "artifact"; - if (artifacts.size() > 1) { - artifactTitle = "artifacts"; - } - Collection artifactsLabels = artifacts.values(); - StringBuilder artifactsLabelBuilder = new StringBuilder(); - - List artifactsLabelsList = new ArrayList(); - artifactsLabelsList.addAll(artifactsLabels); - for (int i = 0; i < artifactsLabelsList.size(); i++) { - ArtifactDefinition artifactDef = artifactsLabelsList.get(i); - artifactsLabelBuilder.append(artifactDef.getArtifactDisplayName()); - if (i < artifactsLabelsList.size() - 1) { - artifactsLabelBuilder.append(";"); - } - } - ResponseFormat responseFormat = getResponseFormat(ActionStatus.COMPONENT_MISSING_MANDATORY_ARTIFACTS, componentType.name().toLowerCase(), artifactTitle, artifactsLabelBuilder.toString()); - - return responseFormat; - } - - public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; - break; - case INVALID_ID: - responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - switch (resultStatus) { - case OK: - responseEnum = ActionStatus.OK; - break; - case ELEMENT_NOT_FOUND: - if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ - responseEnum = ActionStatus.PROPERTY_NOT_FOUND; - } - break; - case INVALID_PROPERTY_DEFAULT_VALUE: - case INVALID_PROPERTY_TYPE: - case INVALID_PROPERTY_VALUE: - case INVALID_PROPERTY_NAME: - case MISSING_ENTRY_SCHEMA_TYPE: - responseEnum = ActionStatus.INVALID_PROPERTY; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - return responseEnum; - } - - public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { - - if (additionalInfoParameterInfo == null) { - additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - } - if (labelOrValue == null) { - labelOrValue = AdditionalInformationEnum.None; - } - - ResponseFormat responseFormat = null; - switch (actionStatus) { - case COMPONENT_NAME_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey()); - break; - case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: - responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); - break; - case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: - responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase()); - break; - case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: - responseFormat = getResponseFormat(actionStatus); - break; - case ADDITIONAL_INFORMATION_NOT_FOUND: - responseFormat = getResponseFormat(actionStatus); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - - return responseFormat; - } - - public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) { - return getResponseFormatAdditionalProperty(actionStatus, null, null, null); - } - - public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; - break; - case NOT_FOUND: - responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) { - ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; - - switch (storageResponse) { - case OK: - responseEnum = ActionStatus.OK; - break; - case CONNECTION_FAILURE: - case GRAPH_IS_LOCK: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - case BAD_REQUEST: - responseEnum = ActionStatus.INVALID_CONTENT; - break; - case ENTITY_ALREADY_EXISTS: - responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; - break; - case SCHEMA_VIOLATION: - responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; - break; - case CANNOT_UPDATE_EXISTING_ENTITY: - responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST; - break; - default: - responseEnum = ActionStatus.GENERAL_ERROR; - break; - } - log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); - return responseEnum; - } - - public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) { - if (groupType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case GROUP_MEMBER_EMPTY: - case GROUP_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, groupType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - - } - - public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) { - if (policyType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case POLICY_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, policyType.getType()); - break; - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - - } - - public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List properties) { - if (dataType == null) { - return getResponseFormat(actionStatus); - } - ResponseFormat responseFormat; - - switch (actionStatus) { - case DATA_TYPE_ALREADY_EXIST: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: - responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); - break; - case DATA_TYPE_DERIVED_IS_MISSING: - responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName()); - break; - case DATA_TYPE_DUPLICATE_PROPERTY: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: - responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); - break; - case DATA_TYPE_CANNOT_HAVE_PROPERTIES: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: - responseFormat = getResponseFormat(actionStatus, dataType.getName()); - break; - - default: - responseFormat = getResponseFormat(actionStatus); - break; - } - return responseFormat; - } + private static final Logger log = LoggerFactory.getLogger(ComponentsUtils.class); + private final AuditingManager auditingManager; + private final ResponseFormatManager responseFormatManager; + + public ComponentsUtils(AuditingManager auditingManager) { + this.auditingManager = auditingManager; + this.responseFormatManager = ResponseFormatManager.getInstance(); + } + + public AuditingManager getAuditingManager() { + return auditingManager; + } + + public Either convertJsonToObject(String data, User user, Class clazz, AuditingActionEnum actionEnum) { + if (data == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); + return Either.right(responseFormat); + } + try { + T obj = parseJsonToObject(data, clazz); + return Either.left(obj); + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum); + return Either.right(responseFormat); + } + } + + public static T parseJsonToObject(String data, Class clazz) { + Type constraintType = new TypeToken() {}.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + log.trace("convert json to object. json=\n{}", data); + return gson.fromJson(data, clazz); + } + + public Either convertJsonToObjectUsingObjectMapper(String data, User user, Class clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { + T component = null; + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + try { + log.trace("convert json to object. json=\n{}", data); + + SimpleModule module = new SimpleModule("customDeserializationModule"); + module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer()); + mapper.registerModule(module); + + component = mapper.readValue(data, clazz); + if (component == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); + return Either.right(responseFormat); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum); + return Either.right(responseFormat); + } + return Either.left(component); + } + + public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) { + return responseFormatManager.getResponseFormat(actionStatus, params); + } + + public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) { + return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params); + } + + public Either, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) { + return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) : + Either.right(getResponseFormat(storageOperationStatus)); + } + + /** + * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he + * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields. + *

+ * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service. + * + * @param actionStatus + * @param resource + * @return + */ + public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) { + if (resource == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case COMPONENT_VERSION_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion()); + break; + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName()); + break; + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + break; + case COMPONENT_IN_USE: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) { + if (resourceName == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) { + if (capabilityType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case CAPABILITY_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) { + if (obj == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat = null; + + switch (actionStatus) { + case MISSING_CAPABILITY_TYPE: + if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)) { + List list = (List) obj; + if (list.get(0) instanceof RequirementDefinition) { + responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object + return responseFormat; + } + } + log.debug("UNKNOWN TYPE : expecting obj as a non empty List"); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + /** + * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he + * received. It's caller's responisibility to fill the passed resource object with needed fields. + * + * @param actionStatus + * @param user + * @return + */ + public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) { + if (user == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat requestErrorWrapper; + switch (actionStatus) { + case INVALID_USER_ID: + requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); + break; + case INVALID_EMAIL_ADDRESS: + requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail()); + break; + case INVALID_ROLE: + requestErrorWrapper = getResponseFormat(actionStatus, user.getRole()); + break; + case USER_NOT_FOUND: + case USER_ALREADY_EXIST: + case USER_INACTIVE: + case USER_HAS_ACTIVE_ELEMENTS: + requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId()); + break; + default: + requestErrorWrapper = getResponseFormat(actionStatus); + break; + } + return requestErrorWrapper; + } + + public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) { + User user = new User(); + user.setUserId(userId); + return getResponseFormatByUser(actionStatus, user); + } + + public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) { + ResponseFormat responseFormat; + + switch (actionStatus) { + case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName); + break; + case DISTRIBUTION_ENVIRONMENT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName); + break; + case DISTRIBUTION_ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) { + ResponseFormat responseFormat; + + switch (actionStatus) { + case RESOURCE_NOT_FOUND: + case ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAudit(User user, String resourceName, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditResource(responseFormat, user, resourceName, actionEnum); + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditAdminUserAction(actionEnum, user, null, null, responseFormat); + return responseFormat; + } + + public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) { + ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT); + log.debug("audit before sending response"); + auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum); + return responseFormat; + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceAuditData prevResFields) { + auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, String resourceName, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, null, resourceName, actionEnum); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum) { + auditResource(responseFormat, modifier, resource, resourceName, actionEnum, ResourceAuditData.newBuilder().build(), null, null); + } + + public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum, + ResourceAuditData prevResFields, String currentArtifactUuid, String artifactData) { + if (actionEnum != null) { + int status = responseFormat.getStatus(); + String message = ""; + String uuid = null; + String resourceCurrVersion = null; + String resourceCurrState = null; + String invariantUUID = null; + String resourceType = ComponentTypeEnum.RESOURCE.getValue(); + String toscaNodeType = null; + + log.trace("Inside auditing for audit action {}", actionEnum); + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + if (resource != null) { + resourceName = resource.getName(); + resourceCurrVersion = resource.getVersion(); + if (resource.getLifecycleState() != null) { + resourceCurrState = resource.getLifecycleState().name(); + } + if (resource.getResourceType() != null) { + resourceType = resource.getResourceType().name(); + } + invariantUUID = resource.getInvariantUUID(); + uuid = resource.getUUID(); + toscaNodeType = resource.getToscaResourceName(); + } + + AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory( + actionEnum, + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .serviceInstanceId(uuid) + .build(), + prevResFields, + ResourceAuditData.newBuilder() + .artifactUuid(currentArtifactUuid) + .state(resourceCurrState) + .version(resourceCurrVersion) + .build(), + resourceType, resourceName, invariantUUID, + modifier, artifactData, null, null, toscaNodeType); + + getAuditingManager().auditEvent(factory); + } + } + + private void updateUserFields(User modifier, EnumMap auditingFields) { + if (modifier != null) { + String firstName = modifier.getFirstName(); + String lastName = modifier.getLastName(); + if (firstName != null || lastName != null) {// to prevent "null + // null" names + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + } + + public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) { + log.trace("Inside auditing"); + int status = responseFormat.getStatus(); + String message = ""; + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + getAuditingManager().auditEvent(auditingFields); + AuditDistribDownloadEventFactory factory = new AuditDistribDownloadEventFactory( + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + distributionData); + getAuditingManager().auditEvent(factory); + } + + public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap additionalParams) { + log.trace("Inside auditing for audit action {}", actionEnum); + int status = responseFormat.getStatus(); + String message = ""; + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + if (additionalParams != null) { + auditingFields.putAll(additionalParams); + } + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap additionalParams) { + log.trace("Inside auditing for audit action {}", actionEnum); + String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER); + String requestURI = request.getRequestURI(); + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + int status = 0; + String message = ""; + if (responseFormat != null) { + status = responseFormat.getStatus(); + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + if (additionalParams != null) { + auditingFields.putAll(additionalParams); + if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, ""); + } + } + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditExternalActivateService(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName(), request, additionalParams); + }public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams); + } + + public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams); + } + + public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams); + } + + public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap additionalParams) { + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER)); + additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ""); + auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams); + } + + public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) { + log.trace("Inside auditing for audit action {}", actionEnum); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + updateUserFields(modifier, auditingFields); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName); + getAuditingManager().auditEvent(auditingFields); + } + + public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) { + + return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE); + } + + public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) { + + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + if (storageResponse == null) { + return responseEnum; + } + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; + break; + case PARENT_RESOURCE_NOT_FOUND: + responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND; + break; + case MULTIPLE_PARENT_RESOURCE_FOUND: + responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND; + break; + case NOT_FOUND: + if (ComponentTypeEnum.RESOURCE == type) { + responseEnum = ActionStatus.RESOURCE_NOT_FOUND; + } else if (ComponentTypeEnum.PRODUCT == type) { + responseEnum = ActionStatus.PRODUCT_NOT_FOUND; + } else { + responseEnum = ActionStatus.SERVICE_NOT_FOUND; + } + break; + case FAILED_TO_LOCK_ELEMENT: + responseEnum = ActionStatus.COMPONENT_IN_USE; + break; + case ARTIFACT_NOT_FOUND: + responseEnum = ActionStatus.ARTIFACT_NOT_FOUND; + break; + case DISTR_ENVIRONMENT_NOT_AVAILABLE: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE; + break; + case DISTR_ENVIRONMENT_NOT_FOUND: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND; + break; + case DISTR_ENVIRONMENT_SENT_IS_INVALID: + responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID; + break; + case DISTR_ARTIFACT_NOT_FOUND: + responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND; + break; + case INVALID_TYPE: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case INVALID_VALUE: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case CSAR_NOT_FOUND: + responseEnum = ActionStatus.CSAR_NOT_FOUND; + break; + case PROPERTY_NAME_ALREADY_EXISTS: + responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY; + break; + case CATEGORY_NOT_FOUND: + responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; + break; + case INVALID_PROPERTY: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromToscaError(ToscaError toscaError) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + if (toscaError == null) { + return responseEnum; + } + switch (toscaError) {// TODO match errors + case NODE_TYPE_CAPABILITY_ERROR: + case NOT_SUPPORTED_TOSCA_TYPE: + case NODE_TYPE_REQUIREMENT_ERROR: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case INVALID_ID: + responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; + break; + case INVALID_PROPERTY: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; + break; + case NOT_FOUND: + if (isRelation) { + responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND; + } else { + responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; + } + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) { + ResponseFormat responseFormat; + + if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { + responseFormat = getResponseFormat(actionStatus, resourceInstanceName); + } + else { + responseFormat = getResponseFormat(actionStatus, serviceName); + } + return responseFormat; + } + + public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) { + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) { + responseFormat = getResponseFormat(actionStatus, resourceInstanceName); + } + else { + responseFormat = getResponseFormat(actionStatus); + } + return responseFormat; + } + + public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case INVALID_ID: + responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST; + break; + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case MATCH_NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST; + break; + case NOT_FOUND: + responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, String comment) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, comment, null, null); + } + + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) { + auditComponent(responseFormat, modifier, component, actionEnum, type, ResourceAuditData.newBuilder().build()); + } + + public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, null, null, null); + } + + + public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, String compName, ComponentTypeEnum type, String comment) { + auditComponent(responseFormat, modifier, null, actionEnum, type, ResourceAuditData.newBuilder().build(), null, compName, comment, null, null); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent) { + auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, currComponent, null, null, null, null); + } + + public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent, String compName, String comment, String artifactData, String did) { + if (actionEnum != null) { + String uuid = null; + String currState = null; + String invariantUUID = null; + String currArtifactUid = null; + String currVersion = null; + String dcurrStatus = null; + String message = ""; + + int status = responseFormat.getStatus(); + + log.trace("Inside auditing for audit action {}", actionEnum); + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + + if (component != null) { + // fields that are filled during creation and might still be empty + if (component.getLifecycleState() != null) { + currState = component.getLifecycleState().name(); + } + uuid = component.getUUID(); + invariantUUID = component.getInvariantUUID(); + currVersion = component.getVersion(); + if (StringUtils.isEmpty(compName)) { + compName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); + } + } + if (currComponent != null) { + currArtifactUid = currComponent.getArtifactUuid(); + dcurrStatus = currComponent.getDistributionStatus(); + if (currState == null) { //probably it was not set + currState = currComponent.getState(); + } + if (currVersion == null) { //probably it was not set + currVersion = currComponent.getVersion(); + } + } + AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory( + actionEnum, + CommonAuditData.newBuilder() + .status(status) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .serviceInstanceId(uuid) + .build(), + prevComponent, + ResourceAuditData.newBuilder() + .artifactUuid(currArtifactUid) + .state(currState) + .version(currVersion) + .distributionStatus(dcurrStatus) + .build(), + type.getValue().replace(" ", ""), compName, invariantUUID, + modifier, artifactData, comment, did, null); + + getAuditingManager().auditEvent(factory); + } + } + + public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) { + + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + + getAuditingManager().auditEvent(auditingFields); + } + + + public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, + String environmentType, String action, String environmentName, String tenantContext) { + getAuditingManager().auditEvent(new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, + environmentType, action, tenantContext)); + } + + public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState, + String topicName, String distributionId, String description, String status, String workloadContext, String tenant) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, tenant); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, workloadContext); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, environmentName); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditAuthEvent(String url, String user, String authStatus, String realm) { + getAuditingManager().auditEvent(new AuditAuthRequestEventFactory( + CommonAuditData.newBuilder() + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + user, url, realm, authStatus)); + } + + public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId); + ThreadLocalsHolder.setUuid(distributionId); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) { + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName); + getAuditingManager().auditEvent(auditingFields); + } + + public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc); + + getAuditingManager().auditEvent(auditingFields); + } + + public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) { + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum, + CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + modifier, consumer); + + getAuditingManager().auditEvent(factory); + } + + public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + if (modifier != null) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + getAuditingManager().auditEvent(auditingFields); + } + + public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) { + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum, + CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + modifier, userBefore, userAfter); + + getAuditingManager().auditEvent(factory); + } + + public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) { + + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + + AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder() + .description(message) + .status(status) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + user); + + getAuditingManager().auditEvent(factory); + } + + public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) { + + EnumMap auditingFields = new EnumMap(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName()); + if (modifier != null) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + } + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details); + int status = responseFormat.getStatus(); + String message = ""; + + if (responseFormat.getMessageId() != null) { + message = responseFormat.getMessageId() + ": "; + } + message += responseFormat.getFormattedMessage(); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message); + getAuditingManager().auditEvent(auditingFields); + } + + public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) { + if (component == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case COMPONENT_VERSION_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion()); + break; + case RESOURCE_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + case COMPONENT_IN_USE: + responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId()); + break; + case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND: + responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + public boolean validateStringNotEmpty(String value) { + return value != null && !value.trim().isEmpty(); + } + + public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) { + ActionStatus responseEnum; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST; + break; + case INVALID_ID: + responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + switch (resultStatus) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ELEMENT_NOT_FOUND: + if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ + responseEnum = ActionStatus.PROPERTY_NOT_FOUND; + } + break; + case INVALID_PROPERTY_DEFAULT_VALUE: + case INVALID_PROPERTY_TYPE: + case INVALID_PROPERTY_VALUE: + case INVALID_PROPERTY_NAME: + case MISSING_ENTRY_SCHEMA_TYPE: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } + + public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { + + if (additionalInfoParameterInfo == null) { + additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + } + if (labelOrValue == null) { + labelOrValue = AdditionalInformationEnum.None; + } + + ResponseFormat responseFormat = null; + switch (actionStatus) { + case COMPONENT_NAME_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey()); + break; + case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: + responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString()); + break; + case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: + responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase()); + break; + case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: + responseFormat = getResponseFormat(actionStatus); + break; + case ADDITIONAL_INFORMATION_NOT_FOUND: + responseFormat = getResponseFormat(actionStatus); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + + return responseFormat; + } + + public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) { + return getResponseFormatAdditionalProperty(actionStatus, null, null, null); + } + + public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS; + break; + case NOT_FOUND: + responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + + switch (storageResponse) { + case OK: + responseEnum = ActionStatus.OK; + break; + case CONNECTION_FAILURE: + case GRAPH_IS_LOCK: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + case BAD_REQUEST: + responseEnum = ActionStatus.INVALID_CONTENT; + break; + case ENTITY_ALREADY_EXISTS: + responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; + break; + case SCHEMA_VIOLATION: + responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST; + break; + case CANNOT_UPDATE_EXISTING_ENTITY: + responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + log.debug("convert storage response {} to action response {}", storageResponse, responseEnum); + return responseEnum; + } + + public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) { + if (groupType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case GROUP_MEMBER_EMPTY: + case GROUP_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, groupType.getType()); + break; + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + + } + + public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) { + if (policyType == null) { + return getResponseFormat(actionStatus); + } + + ResponseFormat responseFormat; + if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) { + responseFormat = getResponseFormat(actionStatus, policyType.getType()); + } + else { + responseFormat = getResponseFormat(actionStatus); + } + return responseFormat; + + } + + public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List properties) { + if (dataType == null) { + return getResponseFormat(actionStatus); + } + ResponseFormat responseFormat; + + switch (actionStatus) { + case DATA_TYPE_ALREADY_EXIST: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: + responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); + break; + case DATA_TYPE_DERIVED_IS_MISSING: + responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName()); + break; + case DATA_TYPE_DUPLICATE_PROPERTY: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: + responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties)); + break; + case DATA_TYPE_CANNOT_HAVE_PROPERTIES: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST: + responseFormat = getResponseFormat(actionStatus, dataType.getName()); + break; + + default: + responseFormat = getResponseFormat(actionStatus); + break; + } + return responseFormat; + } + + + + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java index ddc5ecabe7..b268554ee3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java @@ -20,143 +20,124 @@ package org.openecomp.sdc.be.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.StreamingOutput; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.eclipse.jgit.util.Base64; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.info.ArtifactAccessInfo; import org.openecomp.sdc.be.info.ArtifactAccessList; import org.openecomp.sdc.be.info.ServletJsonResponse; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.StreamingOutput; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; public class DownloadArtifactLogic { - private static Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class.getName()); - - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - public Response downloadArtifact(final String resourceName, final String resourceVersion, final String artifactName, Either getArtifactStatus, String artifactId) { - Response response = null; - - if (getArtifactStatus.isRight()) { - log.debug("Could not find artifact for with id: {}", artifactId); - ResourceUploadStatus status = getArtifactStatus.right().value(); - if (status == status.COMPONENT_NOT_EXIST) - response = Response.status(HttpStatus.SC_NO_CONTENT).build(); - else - response = Response.status(HttpStatus.SC_NOT_FOUND).build(); - - return response; - } - // convert artifact to inputstream - else { - ESArtifactData artifactData = getArtifactStatus.left().value(); - byte[] artifactPayload = artifactData.getDataAsArray(); - - String payloadStr = new String(artifactPayload); - byte[] decodedPayload = artifactPayload; - log.debug("payload is encoded. perform decode"); - decodedPayload = Base64.decode(new String(artifactPayload)); - final InputStream artifactStream = new ByteArrayInputStream(decodedPayload); - log.debug("found artifact for with id: {}", artifactId); - try { - - // outputstream for response - StreamingOutput stream = new StreamingOutput() { - public void write(OutputStream output) throws IOException, WebApplicationException { - try { - IOUtils.copy(artifactStream, output); - } catch (Exception e) { - throw new WebApplicationException(e); - } - } - }; - artifactStream.close(); - return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment; filename = " + artifactName) - // .header(Constants.MD5_HEADER, new - // String(artifactData.getArtifactChecksum())) - .build(); - - } catch (IOException e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Failed to stream artifact data on the response"); - BeEcompErrorManager.getInstance().logBeSystemError("Failed to stream artifact data on the response"); - log.debug("Failed to stream artifact data on the response: {}", e.getMessage(), e); - response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to stream artifact data on the response"); - return response; - } - } - } - - public List convertArtifactList(List artifactsList, String servletPath) { - - List artifactAccessList = new ArrayList(); - for (ESArtifactData artifact : artifactsList) { - ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath); - artifactAccessList.add(accessInfo); - } - return artifactAccessList; - } - - public Response createArtifactListResponse(final String serviceName, Either, ResourceUploadStatus> getArtifactsStatus/* - * List < ? extends IResourceData> artifactsList - */, String servletPath) { - Response response; - List artifactAccessInfos; - if (getArtifactsStatus.isRight()) { - // if there are no artifacts - return No-Content - ResourceUploadStatus status = getArtifactsStatus.right().value(); - if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) { - log.debug("resource {} does not exist", serviceName); - response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build(); - - } else { - log.debug("No content was found for {}", serviceName); - response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build(); - } - return response; - } else { - List artifactsList = getArtifactsStatus.left().value(); - log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName); - artifactAccessInfos = convertArtifactList(artifactsList, servletPath); - - String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos)); - response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); - - return response; - } - } - - public Response buildResponse(int status, String errorMessage) { - - ServletJsonResponse jsonResponse = new ServletJsonResponse(); - jsonResponse.setDescription(errorMessage); - jsonResponse.setSource(Constants.CATALOG_BE); - - Response response = Response.status(status).entity(jsonResponse).build(); - - return response; - } + private static final Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class); + + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public Response downloadArtifact(final String artifactName, Either getArtifactStatus, String artifactId) { + Response response = null; + + if (getArtifactStatus.isRight()) { + log.debug("Could not find artifact for with id: {}", artifactId); + ResourceUploadStatus status = getArtifactStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) + response = Response.status(HttpStatus.SC_NO_CONTENT).build(); + else + response = Response.status(HttpStatus.SC_NOT_FOUND).build(); + + return response; + } + // convert artifact to inputstream + else { + ESArtifactData artifactData = getArtifactStatus.left().value(); + byte[] artifactPayload = artifactData.getDataAsArray(); + + log.debug("payload is encoded. perform decode"); + byte[] decodedPayload = Base64.decode(new String(artifactPayload)); + final InputStream artifactStream = new ByteArrayInputStream(decodedPayload); + log.debug("found artifact for with id: {}", artifactId); + + // outputstream for response + StreamingOutput stream = output -> { + try { + IOUtils.copy(artifactStream, output); + } catch (IOException e) { + log.debug("failed to copy artifact payload into response"); + throw new WebApplicationException(e); + } + }; + return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE) + .header("content-disposition", "attachment; filename = " + artifactName) + .build(); + + } + } + + public List convertArtifactList(List artifactsList, String servletPath) { + + List artifactAccessList = new ArrayList(); + for (ESArtifactData artifact : artifactsList) { + ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath); + artifactAccessList.add(accessInfo); + } + return artifactAccessList; + } + + public Response createArtifactListResponse(final String serviceName, Either, ResourceUploadStatus> getArtifactsStatus/* + * List < ? extends IResourceData> artifactsList + */, String servletPath) { + Response response; + List artifactAccessInfos; + if (getArtifactsStatus.isRight()) { + // if there are no artifacts - return No-Content + ResourceUploadStatus status = getArtifactsStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) { + log.debug("resource {} does not exist", serviceName); + response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build(); + + } else { + log.debug("No content was found for {}", serviceName); + response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build(); + } + return response; + } else { + List artifactsList = getArtifactsStatus.left().value(); + log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName); + artifactAccessInfos = convertArtifactList(artifactsList, servletPath); + + String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos)); + response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); + + return response; + } + } + + public Response buildResponse(int status, String errorMessage) { + + ServletJsonResponse jsonResponse = new ServletJsonResponse(); + jsonResponse.setDescription(errorMessage); + jsonResponse.setSource(Constants.CATALOG_BE); + + Response response = Response.status(status).entity(jsonResponse).build(); + + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java new file mode 100644 index 0000000000..2158508e56 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java @@ -0,0 +1,244 @@ +package org.openecomp.sdc.be.impl; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.SetMultimap; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.javatuples.Pair; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.datamodel.NameIdPair; +import org.openecomp.sdc.be.datamodel.NameIdPairWrapper; +import org.openecomp.sdc.be.datamodel.ServiceRelations; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; + +public class ForwardingPathUtils { + + public static final String FORWARDING_PATH_NODE_NAME = "Forwarding Path"; + public static final String FORWARDER_CAPABILITY = "org.openecomp.capabilities.Forwarder"; + + + public ServiceRelations convertServiceToServiceRelations(Service service) { + ServiceRelations serviceRelations = new ServiceRelations(); + List componentInstances = service.getComponentInstances(); + if (componentInstances == null || componentInstances.isEmpty()) { + return serviceRelations; + } + Set relations = new HashSet<>(); + //@todo get all capabilities and requirements. + SetMultimap nodeToCP = HashMultimap.create(); + componentInstances.forEach(ci -> initNodeToCP(ci, nodeToCP)); + handleRelDef(relations, nodeToCP); + serviceRelations.setRelations(relations); + return serviceRelations; + } + + private void initNodeToCP(ComponentInstance ci, SetMultimap nodeToCP) { + Set capabilities = ci.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()).collect(Collectors.toSet()); + if (!CollectionUtils.isNotEmpty(capabilities)) { + return; + } + Set forwarderCapabilities = capabilities.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet()); + if (!CollectionUtils.isNotEmpty(forwarderCapabilities)) { + return; + } + NameIdPair node = new NameIdPair(ci.getName(), ci.getUniqueId()); + forwarderCapabilities.forEach(fc -> { + NameIdPair capability = new NameIdPair(fc.getName(), fc.getUniqueId(), fc.getOwnerId()); + nodeToCP.put(node, capability); + + }); + + } + + + private void handleRelDef(Set relations, SetMultimap nodeToCP) { + nodeToCP.keySet().forEach(fromNode -> { + NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper(); + nameIdPairWrapper.init(fromNode); + if (!relations.contains(nameIdPairWrapper)) { + relations.add(nameIdPairWrapper); + Collection fromCps = nodeToCP.get(fromNode); + fromCps.forEach(fromCP -> handleFromCp(nodeToCP, nameIdPairWrapper)); + } + }); + + } + + private void handleFromCp(SetMultimap nodeToCP, NameIdPairWrapper wrapper) { + Map> options = toMap(nodeToCP); + + Set cpOptions = options.get(wrapper.getNameIdPair()); + List wrappers = cpOptions.stream().map(cpOption -> createWrapper(cpOption)).collect(Collectors.toList()); + wrappers.forEach(cpOptionWrapper -> { + org.openecomp.sdc.be.datamodel.NameIdPair data = wrapper.getData(); + data.addWrappedData(cpOptionWrapper); + }); + addNodes(wrappers, options); + } + + private void addNodes(List cpOptions, Map> options) { + + cpOptions.forEach(cpOption -> { + Set wrappers = options.keySet().stream().map(option -> createWrapper(option)).collect(Collectors.toSet()); + wrappers.forEach(wrapper -> { + cpOption.getData().addWrappedData(wrapper); + Collection cps = options.get(wrapper.getNameIdPair()); + Set cpsWrappers = cps.stream().map(cp -> new NameIdPairWrapper(cp)).collect(Collectors.toSet()); + cpsWrappers.forEach(cpw -> { + NameIdPair data = wrapper.getData(); + if (!data.containsKey(cpw)) { + data.addWrappedData(cpw); + } + }); + }); + + }); + } + + private NameIdPairWrapper createWrapper(NameIdPair cpOption) { + NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper(); + nameIdPairWrapper.init(new NameIdPair(cpOption)); + return nameIdPairWrapper; + } + + + private Map> toMap(SetMultimap nodeToCP) { + Map> retVal = new HashMap<>(); + nodeToCP.asMap().forEach((nameIdPair, nameIdPairs) -> retVal.put(nameIdPair, new HashSet<>(nameIdPairs))); + return retVal; + } + + + protected ResponseFormatManager getResponseFormatManager() { + return ResponseFormatManager.getInstance(); + } + + public Set findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService, + String componentInstanceId) { + return findForwardingPathToDeleteOnCIDeletion(containerService, componentInstanceId).values().stream() + .map(ForwardingPathDataDefinition::getName).collect(Collectors.toSet()); + } + + private Map findForwardingPathToDeleteOnCIDeletion(Service containerService, + String componentInstanceId) { + return containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCI(entry, componentInstanceId)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + private boolean elementContainsCI(Map.Entry fpEntry, + String componentInstanceId) { + return fpEntry.getValue().getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCI(element, componentInstanceId)); + } + + private boolean elementContainsCI(ForwardingPathElementDataDefinition elementDataDefinitions, + String componentInstanceId) { + return elementDataDefinitions.getFromNode().equals(componentInstanceId) + || elementDataDefinitions.getToNode().equals(componentInstanceId); + } + + public Pair, Map> updateForwardingPathOnVersionChange( + Service containerService, DataForMergeHolder dataHolder, + Component updatedContainerComponent, String newInstanceId) { + Map updated = containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .collect(Collectors.toMap(Map.Entry::getKey, + entry -> updateCI(entry.getValue(), dataHolder.getOrigComponentInstId(),newInstanceId))); + Map deleted = containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue)); + return new Pair<>(updated, deleted); + } + + public Set getForwardingPathsToBeDeletedOnVersionChange( + Service containerService, DataForMergeHolder dataHolder, Component updatedContainerComponent) { + return containerService.getForwardingPaths().entrySet().stream() + .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), + dataHolder.getOrigComponentInstId(), updatedContainerComponent)) + .map(entry -> entry.getValue().getUniqueId()).collect( Collectors.toSet()); + } + + private ForwardingPathDataDefinition updateCI(ForwardingPathDataDefinition inFP, String oldCI, String newCI) { + ForwardingPathDataDefinition retVal = new ForwardingPathDataDefinition(inFP); + List fpList = retVal.getPathElements().getListToscaDataDefinition() + .stream().map(element -> updateElement(element, oldCI, newCI)).collect(Collectors.toList()); + retVal.setPathElements(new ListDataDefinition<>(fpList)); + return retVal; + } + + private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI, + String newCI) { + ForwardingPathElementDataDefinition retVal = new ForwardingPathElementDataDefinition(element); + if (retVal.getFromNode().equals(oldCI)) { + retVal.setFromNode(newCI); + } + if (retVal.getToNode().equals(oldCI)) { + retVal.setToNode(newCI); + } + if (Objects.equals(retVal.getToCPOriginId(),oldCI )) { + retVal.setToCPOriginId(newCI); + } + if (Objects.equals(retVal.getFromCPOriginId(),oldCI)) { + retVal.setFromCPOriginId(newCI); + } + return retVal; + } + + private boolean elementContainsCIAndForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition, + String oldCIId, Component newCI) { + return forwardingPathDataDefinition.getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCIAndForwarder(element, oldCIId, newCI)); + } + + private boolean elementContainsCIAndForwarder(ForwardingPathElementDataDefinition elementDataDefinitions, + String oldCIId, Component newCI) { + return (elementDataDefinitions.getFromNode().equals(oldCIId) && ciContainsForwarder(newCI, + elementDataDefinitions.getFromCP())) + || (elementDataDefinitions.getToNode().equals(oldCIId) && ciContainsForwarder(newCI, + elementDataDefinitions.getToCP())); + } + + private boolean ciContainsForwarder(Component newCI, String capabilityID) { + if (newCI.getCapabilities() == null){ + return false; + } + return newCI.getCapabilities().values() + .stream() + .flatMap(List::stream) + .anyMatch(c -> c.getUniqueId().equals(capabilityID)); + } + + private boolean elementContainsCIAndDoesNotContainForwarder( + ForwardingPathDataDefinition forwardingPathDataDefinition, + String oldCIId, Component newCI) { + return forwardingPathDataDefinition.getPathElements() + .getListToscaDataDefinition().stream() + .anyMatch(element -> elementContainsCIAndDoesNotContainForwarder(element, oldCIId, newCI)); + } + + private boolean elementContainsCIAndDoesNotContainForwarder( + ForwardingPathElementDataDefinition elementDataDefinitions, + String oldCIId, Component newCI) { + return (elementDataDefinitions.getFromNode().equals(oldCIId) && !ciContainsForwarder(newCI, + elementDataDefinitions.getFromCP())) + || (elementDataDefinitions.getToNode().equals(oldCIId) && !ciContainsForwarder(newCI, + elementDataDefinitions.getToCP())); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java index 3a5d9bf85f..c8128a33fc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java @@ -20,30 +20,29 @@ package org.openecomp.sdc.be.impl; -import javax.annotation.Resource; - +import com.google.gson.Gson; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.springframework.stereotype.Component; -import com.google.gson.Gson; +import javax.annotation.Resource; @Component("servletUtils") public class ServletUtils { - @Resource - private ComponentsUtils componentsUtils; - private Gson gson = new Gson(); - @Resource - private IUserBusinessLogic adminManager; - - public ComponentsUtils getComponentsUtils() { - return componentsUtils; - } - - public Gson getGson() { - return gson; - } - - public IUserBusinessLogic getUserAdmin() { - return adminManager; - } + @Resource + private ComponentsUtils componentsUtils; + private Gson gson = new Gson(); + @Resource + private IUserBusinessLogic adminManager; + + public ComponentsUtils getComponentsUtils() { + return componentsUtils; + } + + public Gson getGson() { + return gson; + } + + public IUserBusinessLogic getUserAdmin() { + return adminManager; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java index cb21984a7f..02759289b2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java @@ -20,16 +20,16 @@ package org.openecomp.sdc.be.impl; -import javax.servlet.ServletContext; - import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +import javax.servlet.ServletContext; + public class WebAppContextWrapper { - public WebApplicationContext getWebAppContext(ServletContext context) { + public WebApplicationContext getWebAppContext(ServletContext context) { - return WebApplicationContextUtils.getWebApplicationContext(context); - } + return WebApplicationContextUtils.getWebApplicationContext(context); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java index deb446e32f..d3fcf9f6c0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java @@ -17,143 +17,118 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.be.info; import org.openecomp.sdc.be.resources.data.ESArtifactData; public class ArtifactAccessInfo { - public ArtifactAccessInfo() { - } - - public ArtifactAccessInfo(ESArtifactData artifactData) { - // this.name = artifactData.getArtifactName(); - this.id = artifactData.getId(); - // this.type = artifactData.getArtifactType(); - // this.description = artifactData.getArtifactDescription(); - // this.creator = artifactData.getArtifactCreator(); - // DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL); - // Date creationTimestamp = artifactData.getArtifactCreationTimestamp(); - // this.creationTime = (creationTimestamp != - // null)?dateFormat.format(creationTimestamp): null; - // Date updateTimestamp = artifactData.getArtifactLastUpdateTimestamp(); - // this.lastUpdateTime = (updateTimestamp != - // null)?dateFormat.format(updateTimestamp):null; - // this.lastUpdater = artifactData.getArtifactLastUpdater(); - // if (artifactData.getArtifactChecksum() != null){ - // this.checksum = new String(artifactData.getArtifactChecksum()); - // } else { - // this.checksum = null; - // } - } - - public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) { - // this.name = artifactData.getArtifactName(); - StringBuilder urlBuilder = new StringBuilder(); - urlBuilder = urlBuilder.append(servletContext).append("/"); - // if (ArtifactDataEnum.COMPONENT_ARTIFACT.equals(resource)){ - urlBuilder.append("resources/") - // .append(artifactData.getResourceId()).append("/") - - .append("/artifacts/"); - /* - * }else { ServiceArtifactData serviceArtifact = (ServiceArtifactData)artifactData; urlBuilder.append("services/") .append(serviceArtifact.getServiceName()).append("/") .append(serviceArtifact.getServiceVersion()) .append("/artifacts/") - * .append(serviceArtifact.getNodeTemplateName()) .append("/"); } - */ - // urlBuilder.append(artifactData.getArtifactName()); - this.url = urlBuilder.toString(); - - } - - private String name; - private String url; - private String id; - private String type; - private String description; - private String creator; - private String creationTime; - private String lastUpdater; - private String lastUpdateTime; - private String checksum; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getCreator() { - return creator; - } - - public void setCreator(String creator) { - this.creator = creator; - } - - public String getCreationTime() { - return creationTime; - } - - public void setCreationTime(String creationTime) { - this.creationTime = creationTime; - } - - public String getLastUpdater() { - return lastUpdater; - } - - public void setLastUpdater(String lastUpdater) { - this.lastUpdater = lastUpdater; - } - - public String getLastUpdateTime() { - return lastUpdateTime; - } - - public void setLastUpdateTime(String lastUpdateTime) { - this.lastUpdateTime = lastUpdateTime; - } - - public String getChecksum() { - return checksum; - } - - public void setChecksum(String checksum) { - this.checksum = checksum; - } + public ArtifactAccessInfo() { + } + + public ArtifactAccessInfo(ESArtifactData artifactData) { + this.id = artifactData.getId(); + } + + public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) { + StringBuilder urlBuilder = new StringBuilder(); + urlBuilder = urlBuilder.append(servletContext).append("/"); + urlBuilder.append("resources/") + // .append(artifactData.getResourceId()).append("/") + + .append("/artifacts/"); + this.url = urlBuilder.toString(); + + } + + private String name; + private String url; + private String id; + private String type; + private String description; + private String creator; + private String creationTime; + private String lastUpdater; + private String lastUpdateTime; + private String checksum; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getCreator() { + return creator; + } + + public void setCreator(String creator) { + this.creator = creator; + } + + public String getCreationTime() { + return creationTime; + } + + public void setCreationTime(String creationTime) { + this.creationTime = creationTime; + } + + public String getLastUpdater() { + return lastUpdater; + } + + public void setLastUpdater(String lastUpdater) { + this.lastUpdater = lastUpdater; + } + + public String getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(String lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + public String getChecksum() { + return checksum; + } + + public void setChecksum(String checksum) { + this.checksum = checksum; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java index ddeb0505d9..635a082ad8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java @@ -24,17 +24,17 @@ import java.util.List; public class ArtifactAccessList { - public ArtifactAccessList(List artifacts) { - this.artifacts = artifacts; - } + public ArtifactAccessList(List artifacts) { + this.artifacts = artifacts; + } - private List artifacts; + private List artifacts; - public List getArtifacts() { - return artifacts; - } + public List getArtifacts() { + return artifacts; + } - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java index dfdfeac741..bf257ee4f2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java @@ -24,60 +24,60 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; public class ArtifactDefinitionInfo { - private String uniqueId; - /** Specifies the display name of the artifact. */ - private String artifactName; - private String artifactDisplayName; - private String artifactVersion; - private String artifactUUID; - - public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) { - uniqueId = artifactDefinition.getUniqueId(); - artifactName = artifactDefinition.getArtifactName(); - artifactDisplayName = artifactDefinition.getArtifactDisplayName(); - artifactVersion = artifactDefinition.getArtifactVersion(); - artifactUUID = artifactDefinition.getArtifactUUID(); - - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public String getArtifactDisplayName() { - return artifactDisplayName; - } - - public void setArtifactDisplayName(String artifactDisplayName) { - this.artifactDisplayName = artifactDisplayName; - } - - public String getArtifactVersion() { - return artifactVersion; - } - - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } - - public String getArtifactUUID() { - return artifactUUID; - } - - public void setArtifactUUID(String artifactUUID) { - this.artifactUUID = artifactUUID; - } + private String uniqueId; + /** Specifies the display name of the artifact. */ + private String artifactName; + private String artifactDisplayName; + private String artifactVersion; + private String artifactUUID; + + public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) { + uniqueId = artifactDefinition.getUniqueId(); + artifactName = artifactDefinition.getArtifactName(); + artifactDisplayName = artifactDefinition.getArtifactDisplayName(); + artifactVersion = artifactDefinition.getArtifactVersion(); + artifactUUID = artifactDefinition.getArtifactUUID(); + + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactDisplayName() { + return artifactDisplayName; + } + + public void setArtifactDisplayName(String artifactDisplayName) { + this.artifactDisplayName = artifactDisplayName; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java index f78b7dfead..9b8e81cc7b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java @@ -20,12 +20,9 @@ package org.openecomp.sdc.be.info; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -38,319 +35,316 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import fj.data.Either; +import java.util.*; public class ArtifactTemplateInfo { - public static final String TYPE = "type"; - public static final String FILE_NAME = "fileName"; - public static final String ENV = "env"; - public static final String IS_BASE = "isBase"; - - public static final String CSAR_HEAT = "HEAT"; - public static final String CSAR_ARTIFACT = "artifacts"; - public static final String CSAR_NETWORK = "network"; - public static final String CSAR_VOLUME = "volume"; - public static final String CSAR_NESTED = "nested"; - private static final Object DESC = "description"; - private static Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class.getName()); - String type; - String fileName; - String env; - boolean isBase; - String groupName; - String description; - - List relatedArtifactsInfo; - private static Gson gson = new Gson(); - - public ArtifactTemplateInfo() { - super(); - } - - public ArtifactTemplateInfo(String type, String fileName, String env, List relatedArtifactsInfo) { - super(); - this.type = type; - this.fileName = fileName; - this.env = env; - this.relatedArtifactsInfo = relatedArtifactsInfo; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - public List getRelatedArtifactsInfo() { - return relatedArtifactsInfo; - } - - public void setRelatedArtifactsInfo(List relatedArtifactsInfo) { - this.relatedArtifactsInfo = relatedArtifactsInfo; - } - - public String getGroupName() { - return groupName; - } - - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - public boolean isBase() { - return isBase; - } - - public void setBase(boolean isBase) { - this.isBase = isBase; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]"; - } - - public static Either createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map o, List createdArtifactTemplateInfoList, - ArtifactTemplateInfo parentArtifact) { - String content = gson.toJson(o); - JsonObject jsonElement = new JsonObject(); - ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo(); - - jsonElement = gson.fromJson(content, jsonElement.getClass()); - - Map artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class); - if (artifactTemplateMap.containsKey(TYPE)) - resourceInfo.setType((String) artifactTemplateMap.get(TYPE)); - if (artifactTemplateMap.containsKey(FILE_NAME)) - resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME)); - if (artifactTemplateMap.containsKey(IS_BASE)) - resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE)); - if (artifactTemplateMap.containsKey(ENV)) { - Object envObj = artifactTemplateMap.get(ENV); - String envStr = ""; - if (envObj instanceof String) { - envStr = (String) envObj; - } else if (envObj instanceof Map) { - Map envMap = (Map) envObj; - if (envMap.containsKey(FILE_NAME)) { - envStr = (String) envMap.get(FILE_NAME); - } - } - resourceInfo.setEnv(envStr); - } - if (artifactTemplateMap.containsKey(DESC)) { - resourceInfo.setDescription((String) artifactTemplateMap.get(DESC)); - } else { - resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME)); - } - - boolean artifactTypeExist = false; - String correctType = type; - if (type.equalsIgnoreCase(CSAR_NESTED)) - correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); - else if (type.equalsIgnoreCase(CSAR_VOLUME)) - correctType = ArtifactTypeEnum.HEAT_VOL.getType(); - else if (type.equalsIgnoreCase(CSAR_NETWORK)) - correctType = ArtifactTypeEnum.HEAT_NET.getType(); - else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ - if( parentArtifact != null) - correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); - else - correctType = resourceInfo.type; - } - else if (type.equalsIgnoreCase(CSAR_HEAT)) - correctType = ArtifactTypeEnum.HEAT.getType(); - else - correctType = ArtifactTypeEnum.OTHER.getType(); - Either, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource); - - if (allArtifactTypes.isRight()) { - BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES)); - } - - for (ArtifactType artType : allArtifactTypes.left().value()) { - - if (artType.getName().contains(correctType)) { - resourceInfo.type = artType.getName(); - artifactTypeExist = true; - break; - } - } - - if (!artifactTypeExist) { - BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType); - log.debug("Not supported artifact type = {}" , correctType); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType)); - } - - Either eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact); - if (eitherNeedToCreate.isRight()) - return Either.right(eitherNeedToCreate.right().value()); - Set keys = o.keySet(); - for (String key : keys) { - if (o.get(key) instanceof List) { - List> artifList = (List>) o.get(key); - for (Map relatedArtifactsMap : artifList) { - Either relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo); - if (relatedArtifact.isRight()) - return relatedArtifact; - if (resourceInfo.relatedArtifactsInfo == null) - resourceInfo.relatedArtifactsInfo = new ArrayList(); - resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value()); - } - } - } - return Either.left(resourceInfo); - } - - private static Either validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) { - - if (parentArtifact == null) { - if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) - return Either.left(true); - for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) { - if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type)); - } - } - return Either.left(true); - } else { - List relatedArtifacts = parentArtifact.getRelatedArtifactsInfo(); - if (relatedArtifacts == null || relatedArtifacts.isEmpty()) - return Either.left(true); - for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) { - if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) { - if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName())); - } - } - } - return Either.left(true); - } - } - - private static Either validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) { - - if (parentArtifact == null) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) - && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { - return Either.left(true); - } - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); - } - - if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { - return Either.left(true); - } - return Either.left(true); - } - - private static Either validateEnv(ComponentsUtils componentsUtils, List createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) { - - if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) - return Either.left(true); - if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) - return Either.left(true); - for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) { - // check if artifact with this name already parsed. If parsed check - // env name. it must be the same. - if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) { - if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) { - log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty() - && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) { - log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) { - log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); - } - } - List relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo(); - Either status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo); - if (status.isRight()) - return status; - } - return Either.left(true); - } - - private static Either, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { - - Map deploymentArtifacts = null; - List artifactTypes = new ArrayList(); - - if (parentType.equals(NodeTypeEnum.Service)) { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - } else { - deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - } - if (deploymentArtifacts != null) { - for (String artifactType : deploymentArtifacts.keySet()) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return Either.left(artifactTypes); - } else { - return Either.right(ActionStatus.GENERAL_ERROR); - } - - } - - public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) { - return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0); - } + public static final String TYPE = "type"; + public static final String FILE_NAME = "fileName"; + public static final String ENV = "env"; + public static final String IS_BASE = "isBase"; + + public static final String CSAR_HEAT = "HEAT"; + public static final String CSAR_ARTIFACT = "artifacts"; + public static final String CSAR_NETWORK = "network"; + public static final String CSAR_VOLUME = "volume"; + public static final String CSAR_NESTED = "nested"; + private static final Object DESC = "description"; + private static final Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class); + String type; + String fileName; + String env; + boolean isBase; + String groupName; + String description; + + List relatedArtifactsInfo; + private static Gson gson = new Gson(); + + public ArtifactTemplateInfo() { + super(); + } + + public ArtifactTemplateInfo(String type, String fileName, String env, List relatedArtifactsInfo) { + super(); + this.type = type; + this.fileName = fileName; + this.env = env; + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getEnv() { + return env; + } + + public void setEnv(String env) { + this.env = env; + } + + public List getRelatedArtifactsInfo() { + return relatedArtifactsInfo; + } + + public void setRelatedArtifactsInfo(List relatedArtifactsInfo) { + this.relatedArtifactsInfo = relatedArtifactsInfo; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public boolean isBase() { + return isBase; + } + + public void setBase(boolean isBase) { + this.isBase = isBase; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]"; + } + + public static Either createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map o, List createdArtifactTemplateInfoList, + ArtifactTemplateInfo parentArtifact) { + String content = gson.toJson(o); + JsonObject jsonElement = new JsonObject(); + ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo(); + + jsonElement = gson.fromJson(content, jsonElement.getClass()); + + Map artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class); + if (artifactTemplateMap.containsKey(TYPE)) + resourceInfo.setType((String) artifactTemplateMap.get(TYPE)); + if (artifactTemplateMap.containsKey(FILE_NAME)) + resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME)); + if (artifactTemplateMap.containsKey(IS_BASE)) + resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE)); + if (artifactTemplateMap.containsKey(ENV)) { + Object envObj = artifactTemplateMap.get(ENV); + String envStr = ""; + if (envObj instanceof String) { + envStr = (String) envObj; + } else if (envObj instanceof Map) { + Map envMap = (Map) envObj; + if (envMap.containsKey(FILE_NAME)) { + envStr = (String) envMap.get(FILE_NAME); + } + } + resourceInfo.setEnv(envStr); + } + if (artifactTemplateMap.containsKey(DESC)) { + resourceInfo.setDescription((String) artifactTemplateMap.get(DESC)); + } else { + resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME)); + } + + boolean artifactTypeExist = false; + String correctType = type; + if (type.equalsIgnoreCase(CSAR_NESTED)) + correctType = ArtifactTypeEnum.HEAT_NESTED.getType(); + else if (type.equalsIgnoreCase(CSAR_VOLUME)) + correctType = ArtifactTypeEnum.HEAT_VOL.getType(); + else if (type.equalsIgnoreCase(CSAR_NETWORK)) + correctType = ArtifactTypeEnum.HEAT_NET.getType(); + else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){ + if( parentArtifact != null) + correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType(); + else + correctType = resourceInfo.type; + } + else if (type.equalsIgnoreCase(CSAR_HEAT)) + correctType = ArtifactTypeEnum.HEAT.getType(); + else + correctType = ArtifactTypeEnum.OTHER.getType(); + Either, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource); + + if (allArtifactTypes.isRight()) { + BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES)); + } + + for (ArtifactType artType : allArtifactTypes.left().value()) { + + if (artType.getName().contains(correctType)) { + resourceInfo.type = artType.getName(); + artifactTypeExist = true; + break; + } + } + + if (!artifactTypeExist) { + BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType); + log.debug("Not supported artifact type = {}" , correctType); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType)); + } + + Either eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact); + if (eitherNeedToCreate.isRight()) + return Either.right(eitherNeedToCreate.right().value()); + Set keys = o.keySet(); + for (String key : keys) { + if (o.get(key) instanceof List) { + List> artifList = (List>) o.get(key); + for (Map relatedArtifactsMap : artifList) { + Either relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo); + if (relatedArtifact.isRight()) + return relatedArtifact; + if (resourceInfo.relatedArtifactsInfo == null) + resourceInfo.relatedArtifactsInfo = new ArrayList(); + resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value()); + } + } + } + return Either.left(resourceInfo); + } + + private static Either validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) { + + if (parentArtifact == null) { + if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) + return Either.left(true); + for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) { + if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type)); + } + } + return Either.left(true); + } else { + List relatedArtifacts = parentArtifact.getRelatedArtifactsInfo(); + if (relatedArtifacts == null || relatedArtifacts.isEmpty()) + return Either.left(true); + for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) { + if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) { + if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName())); + } + } + } + return Either.left(true); + } + } + + private static Either validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) { + + if (parentArtifact == null) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) + && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) { + return Either.left(true); + } + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType())); + } + + if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + return Either.left(true); + } + return Either.left(true); + } + + private static Either validateEnv(ComponentsUtils componentsUtils, List createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) { + + if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) + return Either.left(true); + if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) + return Either.left(true); + for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) { + // check if artifact with this name already parsed. If parsed check + // env name. it must be the same. + if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) { + if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) { + log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty() + && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) { + log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) { + log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv())); + } + } + List relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo(); + Either status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo); + if (status.isRight()) + return status; + } + return Either.left(true); + } + + private static Either, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) { + + Map deploymentArtifacts = null; + List artifactTypes = new ArrayList(); + + if (parentType.equals(NodeTypeEnum.Service)) { + deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); + } else { + deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + } + if (deploymentArtifacts != null) { + for (String artifactType : deploymentArtifacts.keySet()) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return Either.left(artifactTypes); + } else { + return Either.right(ActionStatus.GENERAL_ERROR); + } + + } + + public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) { + return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java index 249b420908..5d635f05ff 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java @@ -20,29 +20,29 @@ package org.openecomp.sdc.be.info; -import java.util.List; - import org.openecomp.sdc.be.model.ArtifactType; +import java.util.List; + public class ArtifactTypesInfo { - Integer heatDefaultTimeout = 60; - List artifactTypes; + Integer heatDefaultTimeout = 60; + List artifactTypes; - public List getArtifactTypes() { - return artifactTypes; - } + public List getArtifactTypes() { + return artifactTypes; + } - public void setArtifactTypes(List artifactTypes) { - this.artifactTypes = artifactTypes; - } + public void setArtifactTypes(List artifactTypes) { + this.artifactTypes = artifactTypes; + } - public Integer getHeatDefaultTimeout() { - return heatDefaultTimeout; - } + public Integer getHeatDefaultTimeout() { + return heatDefaultTimeout; + } - public void setHeatDefaultTimeout(Integer heatDefaultTimeout) { - this.heatDefaultTimeout = heatDefaultTimeout; - } + public void setHeatDefaultTimeout(Integer heatDefaultTimeout) { + this.heatDefaultTimeout = heatDefaultTimeout; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java index b2fa493443..a7847a164d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java @@ -24,29 +24,29 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; public class CreateAndAssotiateInfo { - private ComponentInstance node; - private RequirementCapabilityRelDef associate; - - public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) { - super(); - this.node = node; - this.associate = associate; - } - - public ComponentInstance getNode() { - return node; - } - - public void setNode(ComponentInstance node) { - this.node = node; - } - - public RequirementCapabilityRelDef getAssociate() { - return associate; - } - - public void setAssociate(RequirementCapabilityRelDef associate) { - this.associate = associate; - } + private ComponentInstance node; + private RequirementCapabilityRelDef associate; + + public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) { + super(); + this.node = node; + this.associate = associate; + } + + public ComponentInstance getNode() { + return node; + } + + public void setNode(ComponentInstance node) { + this.node = node; + } + + public RequirementCapabilityRelDef getAssociate() { + return associate; + } + + public void setAssociate(RequirementCapabilityRelDef associate) { + this.associate = associate; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java index d0f3ff868e..795d5f6046 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java @@ -24,39 +24,39 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public enum DistributionStatus { - DEPLOYED("Deployed", "DEPLOYED"); - - private String name; - private String auditingStatus; - - private static Logger log = LoggerFactory.getLogger(DistributionStatus.class.getName()); - - DistributionStatus(String name, String auditingStatus) { - this.name = name; - this.auditingStatus = auditingStatus; - } - - public String getName() { - return name; - } - - public String getAuditingStatus() { - return auditingStatus; - } - - public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) { - DistributionStatus res = null; - DistributionStatus[] values = values(); - for (DistributionStatus value : values) { - if (value.getAuditingStatus().equals(auditingStatus)) { - res = value; - break; - } - } - if (res == null) { - log.debug("No DistributionStatus is mapped to name {}", auditingStatus); - } - return res; - } + DEPLOYED("Deployed", "DEPLOYED"); + + private String name; + private String auditingStatus; + + private static final Logger log = LoggerFactory.getLogger(DistributionStatus.class); + + DistributionStatus(String name, String auditingStatus) { + this.name = name; + this.auditingStatus = auditingStatus; + } + + public String getName() { + return name; + } + + public String getAuditingStatus() { + return auditingStatus; + } + + public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) { + DistributionStatus res = null; + DistributionStatus[] values = values(); + for (DistributionStatus value : values) { + if (value.getAuditingStatus().equals(auditingStatus)) { + res = value; + break; + } + } + if (res == null) { + log.debug("No DistributionStatus is mapped to name {}", auditingStatus); + } + return res; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java index 6f7596cd5f..dd8ef32124 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java @@ -24,68 +24,68 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; public class DistributionStatusInfo { - String omfComponentID; - String timestamp; - String url; - String status; - String errorReason; - - public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) { - super(); - omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName()); - timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime(); - url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL(); - status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus(); - errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName()); - - } - - public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) { - super(); - this.omfComponentID = omfComponentID; - this.timestamp = timestamp; - this.url = url; - this.status = status; - } - - public String getOmfComponentID() { - return omfComponentID; - } - - public void setOmfComponentID(String omfComponentID) { - this.omfComponentID = omfComponentID; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } + String omfComponentID; + String timestamp; + String url; + String status; + String errorReason; + + public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) { + super(); + omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName()); + timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime(); + url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL(); + status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus(); + errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName()); + + } + + public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) { + super(); + this.omfComponentID = omfComponentID; + this.timestamp = timestamp; + this.url = url; + this.status = status; + } + + public String getOmfComponentID() { + return omfComponentID; + } + + public void setOmfComponentID(String omfComponentID) { + this.omfComponentID = omfComponentID; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java index ab122efc74..1f3fb90f78 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java @@ -24,14 +24,14 @@ import java.util.List; public class DistributionStatusListResponse { - private List distribStatusInfoList; + private List distribStatusInfoList; - public List getDistributionStatusList() { - return distribStatusInfoList; - } + public List getDistributionStatusList() { + return distribStatusInfoList; + } - public void setDistributionStatusList(List distribStatusInfoList) { - this.distribStatusInfoList = distribStatusInfoList; - } + public void setDistributionStatusList(List distribStatusInfoList) { + this.distribStatusInfoList = distribStatusInfoList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java index dfa481d34d..533ca7e99f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java @@ -21,54 +21,54 @@ package org.openecomp.sdc.be.info; public class DistributionStatusOfServiceInfo { - String distributionID; - String timestamp; - String userId; - String deployementStatus; + String distributionID; + String timestamp; + String userId; + String deployementStatus; - public DistributionStatusOfServiceInfo() { - super(); + public DistributionStatusOfServiceInfo() { + super(); - } + } - public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) { - super(); - this.distributionID = distributionID; - this.timestamp = timestamp; - this.userId = userId; - this.deployementStatus = deployementStatus; - } + public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) { + super(); + this.distributionID = distributionID; + this.timestamp = timestamp; + this.userId = userId; + this.deployementStatus = deployementStatus; + } - public String getDistributionID() { - return distributionID; - } + public String getDistributionID() { + return distributionID; + } - public void setDistributionID(String distributionID) { - this.distributionID = distributionID; - } + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } - public String getTimestamp() { - return timestamp; - } + public String getTimestamp() { + return timestamp; + } - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } - public String getUserId() { - return userId; - } + public String getUserId() { + return userId; + } - public void setUserId(String userId) { - this.userId = userId; - } + public void setUserId(String userId) { + this.userId = userId; + } - public String getDeployementStatus() { - return deployementStatus; - } + public String getDeployementStatus() { + return deployementStatus; + } - public void setDeployementStatus(String deployementStatus) { - this.deployementStatus = deployementStatus; - } + public void setDeployementStatus(String deployementStatus) { + this.deployementStatus = deployementStatus; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java index 8415736be1..023645fa2d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java @@ -24,14 +24,14 @@ import java.util.List; public class DistributionStatusOfServiceListResponce { - private List distribStatusOfServiceInfoList; + private List distribStatusOfServiceInfoList; - public List getDistributionStatusOfServiceList() { - return distribStatusOfServiceInfoList; - } + public List getDistributionStatusOfServiceList() { + return distribStatusOfServiceInfoList; + } - public void setDistributionStatusOfServiceList(List distribStatusOfServiceInfoList) { - this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList; - } + public void setDistributionStatusOfServiceList(List distribStatusOfServiceInfoList) { + this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java index ea495267bd..f49315c0d0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java @@ -20,157 +20,157 @@ package org.openecomp.sdc.be.info; -import java.util.List; - import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupProperty; +import java.util.List; + public class GroupDefinitionInfo { - private String name; - - // the id is unique per group instance on graph. - private String uniqueId; - - // the id is unique per group instance on graph. - private String groupInstanceUniqueId; - - // the group UUID should be changed when one of the artifacts/component - // instances has been changed. - private String groupUUID; - - // version should be changed when there is a change to the group's metadata - // or to the groups members - // (not necessarily when the VF version is changed). This field cannot be - // updated by user - private String version; - - private String invariantUUID; - private String customizationUUID; - - Boolean isBase = null; - - // artifacts - list of artifact uid. All artifacts in the group must already - // be uploaded to the VF - private List artifacts; - - private List properties; - - public GroupDefinitionInfo() { - super(); - } - - public GroupDefinitionInfo(GroupDefinition other) { - this.setName(other.getName()); - this.setUniqueId(other.getUniqueId()); - this.setVersion(other.getVersion()); - this.setGroupUUID(other.getGroupUUID()); - this.setInvariantUUID(other.getInvariantUUID()); - this.setProperties(other.convertToGroupProperties()); - - - } - - public GroupDefinitionInfo(GroupInstance other) { - this.setName(other.getGroupName()); - this.setUniqueId(other.getGroupUid()); - this.setGroupInstanceUniqueId(other.getUniqueId()); - this.setVersion(other.getVersion()); - this.setGroupUUID(other.getGroupUUID()); - this.setCustomizationUUID(other.getCustomizationUUID()); - this.setInvariantUUID(other.getInvariantUUID()); - this.setProperties(other.convertToGroupInstancesProperties()); - - - } - - public String getInvariantUUID() { - return invariantUUID; - } - - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getGroupUUID() { - return groupUUID; - } - - public void setGroupUUID(String groupUUID) { - this.groupUUID = groupUUID; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - - public String getCustomizationUUID() { - return customizationUUID; - } - - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public Boolean getIsBase() { - return isBase; - } - - public void setIsBase(Boolean isBase) { - this.isBase = isBase; - } - - public List getArtifacts() { - return artifacts; - } - - public void setArtifacts(List artifacts) { - this.artifacts = artifacts; - } - - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - - - public String getGroupInstanceUniqueId() { - return groupInstanceUniqueId; - } - - public void setGroupInstanceUniqueId(String groupInstanceUniqueId) { - this.groupInstanceUniqueId = groupInstanceUniqueId; - } - - @Override - public String toString() { - return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]"; - } - + private String name; + + // the id is unique per group instance on graph. + private String uniqueId; + + // the id is unique per group instance on graph. + private String groupInstanceUniqueId; + + // the group UUID should be changed when one of the artifacts/component + // instances has been changed. + private String groupUUID; + + // version should be changed when there is a change to the group's metadata + // or to the groups members + // (not necessarily when the VF version is changed). This field cannot be + // updated by user + private String version; + + private String invariantUUID; + private String customizationUUID; + + Boolean isBase = null; + + // artifacts - list of artifact uid. All artifacts in the group must already + // be uploaded to the VF + private List artifacts; + + private List properties; + + public GroupDefinitionInfo() { + super(); + } + + public GroupDefinitionInfo(GroupDefinition other) { + this.setName(other.getName()); + this.setUniqueId(other.getUniqueId()); + this.setVersion(other.getVersion()); + this.setGroupUUID(other.getGroupUUID()); + this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupProperties()); + + + } + + public GroupDefinitionInfo(GroupInstance other) { + this.setName(other.getGroupName()); + this.setUniqueId(other.getGroupUid()); + this.setGroupInstanceUniqueId(other.getUniqueId()); + this.setVersion(other.getVersion()); + this.setGroupUUID(other.getGroupUUID()); + this.setCustomizationUUID(other.getCustomizationUUID()); + this.setInvariantUUID(other.getInvariantUUID()); + this.setProperties(other.convertToGroupInstancesProperties()); + + + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getGroupUUID() { + return groupUUID; + } + + public void setGroupUUID(String groupUUID) { + this.groupUUID = groupUUID; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public Boolean getIsBase() { + return isBase; + } + + public void setIsBase(Boolean isBase) { + this.isBase = isBase; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + + public String getGroupInstanceUniqueId() { + return groupInstanceUniqueId; + } + + public void setGroupInstanceUniqueId(String groupInstanceUniqueId) { + this.groupInstanceUniqueId = groupInstanceUniqueId; + } + + @Override + public String toString() { + return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java index 4a7e925639..301cffafdc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java @@ -21,36 +21,36 @@ package org.openecomp.sdc.be.info; public class GroupTemplateInfo { - String groupName; - boolean isBase; - ArtifactTemplateInfo artifactTemplateInfo; + String groupName; + boolean isBase; + ArtifactTemplateInfo artifactTemplateInfo; - public GroupTemplateInfo() { - super(); - } + public GroupTemplateInfo() { + super(); + } - public String getGroupName() { - return groupName; - } + public String getGroupName() { + return groupName; + } - public void setGroupName(String groupName) { - this.groupName = groupName; - } + public void setGroupName(String groupName) { + this.groupName = groupName; + } - public boolean isBase() { - return isBase; - } + public boolean isBase() { + return isBase; + } - public void setBase(boolean isBase) { - this.isBase = isBase; - } + public void setBase(boolean isBase) { + this.isBase = isBase; + } - public ArtifactTemplateInfo getArtifactTemplateInfo() { - return artifactTemplateInfo; - } + public ArtifactTemplateInfo getArtifactTemplateInfo() { + return artifactTemplateInfo; + } - public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) { - this.artifactTemplateInfo = artifactTemplateInfo; - } + public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) { + this.artifactTemplateInfo = artifactTemplateInfo; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java index 62ee5b6f81..e4b6f35cba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java @@ -20,150 +20,145 @@ package org.openecomp.sdc.be.info; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.model.ArtifactDefinition; +import java.util.*; public class MergedArtifactInfo { - private List createdArtifact; - private ArtifactTemplateInfo jsonArtifactTemplate; - private Set parsetArtifactsNames; - - public List getCreatedArtifact() { - return createdArtifact; - } - - public void setCreatedArtifact(List createdArtifact) { - this.createdArtifact = createdArtifact; - parsetArtifactsNames = new HashSet(); - parsetArtifactsNames.add(jsonArtifactTemplate.getFileName()); - List relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { - this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames); - } - - } - - public ArtifactTemplateInfo getJsonArtifactTemplate() { - return jsonArtifactTemplate; - } - - public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) { - this.jsonArtifactTemplate = jsonArtifactTemplate; - } - - public List getListToAssociateArtifactToGroup() { - List resList = new ArrayList(); - List relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getNewArtifactsInGroup(resList, relatedArtifacts); - } - return resList; - } - - public List getListToDissotiateArtifactFromGroup(List deletedArtifacts) { - List resList = new ArrayList(); - for (ArtifactDefinition artifactDefinition : createdArtifact) { - boolean isDissotiate = true; - if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){ - isDissotiate = false; - }else{ - if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){ - Optional op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); - if(op.isPresent()){ - ArtifactDefinition generatedFromArt = op.get(); - if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){ - isDissotiate = false; - } - } - else{ - isDissotiate = true; - } - - } - } - if (isDissotiate) { - boolean isDeleted = false; - for (ArtifactDefinition deletedArtifact : deletedArtifacts) { - if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) { - isDeleted = true; - break; - } - - } - if (!isDeleted) - resList.add(artifactDefinition); - } - - } - - return resList; - } - - public List> getListToUpdateArtifactInGroup() { - List> resList = new ArrayList>(); - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) { - resList.add(new ImmutablePair(artifactDefinition, jsonArtifactTemplate)); - } - } - List relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getUpdateArtifactsInGroup(resList, relatedArtifacts); - } - return resList; - } - - private void getUpdateArtifactsInGroup(List> resList, List jsonArtifacts) { - - for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { - - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { - resList.add(new ImmutablePair(artifactDefinition, artifactTemplateInfo)); - } - } - - List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getUpdateArtifactsInGroup(resList, relatedArtifacts); - } - } - } - - private void getNewArtifactsInGroup(List resList, List jsonArtifacts) { - - for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { - boolean isNewArtifact = true; - for (ArtifactDefinition artifactDefinition : createdArtifact) { - if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { - isNewArtifact = false; - } - } - if (isNewArtifact) - resList.add(artifactTemplateInfo); - List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - getNewArtifactsInGroup(resList, relatedArtifacts); - } - } - } - - private void createArtifactsGroupSet(List parsedGroupTemplateList, Set parsedArtifactsName) { - - for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { - parsedArtifactsName.add(parsedGroupTemplate.getFileName()); - List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); - if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { - createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); - } - } - } + private List createdArtifact; + private ArtifactTemplateInfo jsonArtifactTemplate; + private Set parsetArtifactsNames; + + public List getCreatedArtifact() { + return createdArtifact; + } + + public void setCreatedArtifact(List createdArtifact) { + this.createdArtifact = createdArtifact; + parsetArtifactsNames = new HashSet(); + parsetArtifactsNames.add(jsonArtifactTemplate.getFileName()); + List relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) { + this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames); + } + + } + + public ArtifactTemplateInfo getJsonArtifactTemplate() { + return jsonArtifactTemplate; + } + + public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) { + this.jsonArtifactTemplate = jsonArtifactTemplate; + } + + public List getListToAssociateArtifactToGroup() { + List resList = new ArrayList(); + List relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getNewArtifactsInGroup(resList, relatedArtifacts); + } + return resList; + } + + public List getListToDissotiateArtifactFromGroup(List deletedArtifacts) { + List resList = new ArrayList(); + for (ArtifactDefinition artifactDefinition : createdArtifact) { + boolean isDissotiate = true; + if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){ + isDissotiate = false; + }else{ + if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){ + Optional op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); + if(op.isPresent()){ + ArtifactDefinition generatedFromArt = op.get(); + if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){ + isDissotiate = false; + } + } + else{ + isDissotiate = true; + } + + } + } + if (isDissotiate) { + boolean isDeleted = false; + for (ArtifactDefinition deletedArtifact : deletedArtifacts) { + if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) { + isDeleted = true; + break; + } + + } + if (!isDeleted) + resList.add(artifactDefinition); + } + + } + + return resList; + } + + public List> getListToUpdateArtifactInGroup() { + List> resList = new ArrayList>(); + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) { + resList.add(new ImmutablePair(artifactDefinition, jsonArtifactTemplate)); + } + } + List relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getUpdateArtifactsInGroup(resList, relatedArtifacts); + } + return resList; + } + + private void getUpdateArtifactsInGroup(List> resList, List jsonArtifacts) { + + for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { + + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { + resList.add(new ImmutablePair(artifactDefinition, artifactTemplateInfo)); + } + } + + List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getUpdateArtifactsInGroup(resList, relatedArtifacts); + } + } + } + + private void getNewArtifactsInGroup(List resList, List jsonArtifacts) { + + for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) { + boolean isNewArtifact = true; + for (ArtifactDefinition artifactDefinition : createdArtifact) { + if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) { + isNewArtifact = false; + } + } + if (isNewArtifact) + resList.add(artifactTemplateInfo); + List relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + getNewArtifactsInGroup(resList, relatedArtifacts); + } + } + } + + private void createArtifactsGroupSet(List parsedGroupTemplateList, Set parsedArtifactsName) { + + for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) { + parsedArtifactsName.add(parsedGroupTemplate.getFileName()); + List relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo(); + if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) { + createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java new file mode 100644 index 0000000000..766581bd62 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java @@ -0,0 +1,41 @@ +package org.openecomp.sdc.be.info; + +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class NodeTypeInfoToUpdateArtifacts { + + private String nodeName; + private Map>> nodeTypesArtifactsToHandle; + + + public NodeTypeInfoToUpdateArtifacts(String nodeName, + Map>> nodeTypesArtifactsToHandle) { + super(); + this.nodeName = nodeName; + this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle; + } + + public String getNodeName() { + return nodeName; + } + + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } + + public Map>> getNodeTypesArtifactsToHandle() { + return nodeTypesArtifactsToHandle; + } + + public void setNodeTypesArtifactsToHandle( + Map>> nodeTypesArtifactsToHandle) { + this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle; + } + + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java new file mode 100644 index 0000000000..4d27713e22 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java @@ -0,0 +1,123 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public final class OperationalEnvInfo { + @JsonIgnore + private static ObjectMapper objectMapper = new ObjectMapper(); + + @JsonIgnore + private static final Logger logger = LoggerFactory.getLogger(OperationalEnvInfo.class); + + @JsonProperty("operational-environment-id") + private String operationalEnvId; + + @JsonProperty("operational-environment-name") + private String operationalEnvName; + + @JsonProperty("operational-environment-type") + private String operationalEnvType; + + @JsonProperty("operational-environment-status") + private String operationalEnvStatus; + + @JsonProperty("tenant-context") + private String tenantContext; + + @JsonProperty("workload-context") + private String workloadContext; + + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("relationship-list") + private RelationshipList relationships; + + public String getOperationalEnvId() { + return operationalEnvId; + } + + public void setOperationalEnvId(String operationalEnvId) { + this.operationalEnvId = operationalEnvId; + } + + public String getOperationalEnvName() { + return operationalEnvName; + } + + public void setOperationalEnvName(String operationalEnvName) { + this.operationalEnvName = operationalEnvName; + } + + public String getOperationalEnvType() { + return operationalEnvType; + } + + public void setOperationalEnvType(String operationalEnvType) { + this.operationalEnvType = operationalEnvType; + } + + public String getOperationalEnvStatus() { + return operationalEnvStatus; + } + + public void setOperationalEnvStatus(String operationalEnvStatus) { + this.operationalEnvStatus = operationalEnvStatus; + } + + public String getTenantContext() { + return tenantContext; + } + + public void setTenantContext(String tenantContext) { + this.tenantContext = tenantContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public RelationshipList getRelationships() { + return relationships; + } + + public void setRelationships(RelationshipList relationships) { + this.relationships = relationships; + } + + @Override + public String toString() { + try { + return objectMapper.writeValueAsString(this); + } + catch (JsonProcessingException e) { + logger.debug("Convert object to string failed with exception. ", e); + return StringUtils.EMPTY; + } + } + + public static OperationalEnvInfo createFromJson(String json) throws IOException { + return objectMapper.readValue(json, OperationalEnvInfo.class); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java new file mode 100644 index 0000000000..5684c9b57f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public final class RelatedToProperty { + + @JsonProperty("property-key") + private String propertyKey; + + @JsonProperty("property-value") + private String propertyValue; + + public String getPropertyKey() { + return propertyKey; + } + + public void setPropertyKey(String propertyKey) { + this.propertyKey = propertyKey; + } + + public String getPropertyValue() { + return propertyValue; + } + + public void setPropertyValue(String propertyValue) { + this.propertyValue = propertyValue; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java new file mode 100644 index 0000000000..fba6632698 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +public final class Relationship { + + @JsonProperty("related-to") + private String relatedTo; + + @JsonProperty(value="relationship-label") + private String relationshipLabel; + + @JsonProperty(value="related-link", required=false) + private String relatedLink; + + @JsonProperty("relationship-data") + private List relationshipData; + + @JsonProperty("related-to-property") + private List relatedToProperty; + + public String getRelatedTo() { + return relatedTo; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } + + public List getRelationshipData() { + if(relationshipData == null) { + relationshipData = new ArrayList<>(); + } + return relationshipData; + } + + public void setRelationshipData(List relationshipData) { + this.relationshipData = relationshipData; + } + + public String getRelationshipLabel() { + return relationshipLabel; + } + + public void setRelationshipLabel(String relationshipLabel) { + this.relationshipLabel = relationshipLabel; + } + + public List getRelatedToProperty() { + if(relatedToProperty == null) { + relatedToProperty = new ArrayList<>(); + } + return relatedToProperty; + } + + public void setRelatedToProperty(List relatedToProperty) { + this.relatedToProperty = relatedToProperty; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java new file mode 100644 index 0000000000..2b01daecd4 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.be.info; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public final class RelationshipData { + + @JsonProperty("relationship-key") + private String relationshipKey; + + @JsonProperty("relationship-value") + private String relationshipValue; + + public void setRelationshipkey(String relationshipKey) { + this.relationshipKey = relationshipKey; + } + + public String getRelationshipKey() { + return this.relationshipKey; + } + + public void setRelationshipValue(String relationshipValue) { + this.relationshipValue = relationshipValue; + } + + public String getRelationshipValue() { + return this.relationshipValue; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java new file mode 100644 index 0000000000..6a09a84d6e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.info; + +import java.util.ArrayList; +import java.util.List; + +public class RelationshipList { + private List relationship; + + public List getRelationship() { + if(relationship == null) { + relationship = new ArrayList<>(); + } + return relationship; + } + + public void setRelationship(List relationship) { + this.relationship = relationship; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java index 457c49ee8e..99395350cb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java @@ -24,28 +24,28 @@ import java.util.List; public class ServiceInfo { - private String name; - private List versions; + private String name; + private List versions; - public ServiceInfo(String serviceName, List list) { - this.name = serviceName; - this.versions = list; - } + public ServiceInfo(String serviceName, List list) { + this.name = serviceName; + this.versions = list; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public List getVersions() { - return versions; - } + public List getVersions() { + return versions; + } - public void setVersions(List versions) { - this.versions = versions; - } + public void setVersions(List versions) { + this.versions = versions; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java index 13f8a1307f..32c7c54528 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java @@ -22,32 +22,30 @@ package org.openecomp.sdc.be.info; public class ServiceVersionInfo { - // private String serviceName; - private String version; - private String url; - - public ServiceVersionInfo(String serviceName, String serviceVersion, String context) { - super(); - // this.serviceName = serviceName; - this.version = serviceVersion; - StringBuilder sb = new StringBuilder(context); - sb.append("services/").append(serviceName).append("/").append(serviceVersion); - url = sb.toString(); - } - - public String getVersion() { - return version; - } - - public void setVersion(String serviceVersion) { - this.version = serviceVersion; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } + private String version; + private String url; + + public ServiceVersionInfo(String serviceName, String serviceVersion, String context) { + super(); + this.version = serviceVersion; + StringBuilder sb = new StringBuilder(context); + sb.append("services/").append(serviceName).append("/").append(serviceVersion); + url = sb.toString(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String serviceVersion) { + this.version = serviceVersion; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java index 9c26cf5959..00f41ad434 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java @@ -23,13 +23,13 @@ package org.openecomp.sdc.be.info; import java.util.List; public class ServicesWrapper { - private List services; + private List services; - public List getServices() { - return services; - } + public List getServices() { + return services; + } - public void setServices(List services) { - this.services = services; - } + public void setServices(List services) { + this.services = services; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java index 5559311e9e..ae2032eb43 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java @@ -22,23 +22,23 @@ package org.openecomp.sdc.be.info; public class ServletJsonResponse { - String source; - String description; + String source; + String description; - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getSource() { - return source; - } + public String getSource() { + return source; + } - public void setSource(String source) { - this.source = source; - } + public void setSource(String source) { + this.source = source; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java index 11b27af7a1..031477cfe9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java @@ -24,46 +24,46 @@ import java.util.List; public class ToscaNodeTypeInfo { - private String nodeName; - private String templateVersion; - private List interfaces; - private String iconPath; + private String nodeName; + private String templateVersion; + private List interfaces; + private String iconPath; - public String getNodeName() { - return nodeName; - } + public String getNodeName() { + return nodeName; + } - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } - public String getTemplateVersion() { - return templateVersion; - } + public String getTemplateVersion() { + return templateVersion; + } - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } - public List getInterfaces() { - return interfaces; - } + public List getInterfaces() { + return interfaces; + } - public void setInterfaces(List interfaces) { - this.interfaces = interfaces; - } + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } - public String getIconPath() { - return iconPath; - } + public String getIconPath() { + return iconPath; + } - public void setIconPath(String iconPath) { - this.iconPath = iconPath; - } + public void setIconPath(String iconPath) { + this.iconPath = iconPath; + } - @Override - public String toString() { - return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; - } + @Override + public String toString() { + return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java index 25bab766bf..05fa3193c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java @@ -24,14 +24,14 @@ import java.util.List; public class ToscaNodeTypeInterface { - List scripts; + List scripts; - public List getScripts() { - return scripts; - } + public List getScripts() { + return scripts; + } - public void setScripts(List scripts) { - this.scripts = scripts; - } + public void setScripts(List scripts) { + this.scripts = scripts; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 83cda6ef87..f895577c5d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -41,54 +41,53 @@ import org.slf4j.LoggerFactory; public class BEAppContextListener extends AppContextListener implements ServletContextListener { - private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; - private static Logger log = LoggerFactory.getLogger(BEAppContextListener.class.getName()); - - public void contextInitialized(ServletContextEvent context) { + private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; + private static final Logger log = LoggerFactory.getLogger(BEAppContextListener.class); - super.contextInitialized(context); + public void contextInitialized(ServletContextEvent context) { - ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); - log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName()); + super.contextInitialized(context); - context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); + ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); + log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName()); - WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper(); - context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper); + context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager); - DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic(); - context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic); + WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper(); + context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper); - context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); + DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic(); + context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic); - // Monitoring service - BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); - bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); + context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context)); - log.debug("After executing {}", this.getClass()); + // Monitoring service + BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); + bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); - } - - private String getVersionFromManifest(ServletContextEvent context) { - ServletContext servletContext = context.getServletContext(); - InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); + log.debug("After executing {}", this.getClass()); - String version = null; - try { - Manifest mf = new Manifest(inputStream); - Attributes atts = mf.getMainAttributes(); - version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR); - if (version == null || version.isEmpty()) { - log.warn("failed to read ASDC version from MANIFEST."); - } else { - log.info("ASDC version from MANIFEST is {}", version); - } + } - } catch (IOException e) { - log.warn("failed to read ASDC version from MANIFEST", e.getMessage()); - } + private String getVersionFromManifest(ServletContextEvent context) { + ServletContext servletContext = context.getServletContext(); + InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME); - return version; - } + String version = null; + try { + Manifest mf = new Manifest(inputStream); + Attributes atts = mf.getMainAttributes(); + version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR); + if (version == null || version.isEmpty()) { + log.warn("failed to read ASDC version from MANIFEST."); + } else { + log.info("ASDC version from MANIFEST is {}", version); + } + + } catch (IOException e) { + log.warn("failed to read ASDC version from MANIFEST", e); + } + return version; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java new file mode 100644 index 0000000000..216e55a2b1 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.mixin; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; +import org.openecomp.sdc.be.view.Mixin; +import org.openecomp.sdc.be.view.MixinTarget; + +@MixinTarget(target = GroupTypeDataDefinition.class) +public abstract class GroupTypeMixin extends Mixin { + + @JsonProperty + abstract String getType(); + @JsonProperty + abstract String getVersion(); + @JsonProperty + abstract String getUniqueId(); + +} + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java new file mode 100644 index 0000000000..0fd86e1ced --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.mixin; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition; +import org.openecomp.sdc.be.view.Mixin; +import org.openecomp.sdc.be.view.MixinTarget; + +@MixinTarget(target = PolicyTypeDataDefinition.class) +public abstract class PolicyTypeMixin extends Mixin { + + @JsonProperty + abstract String getType(); + @JsonProperty + abstract String getVersion(); + @JsonProperty + abstract String getUniqueId(); + +} + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java index 6be300d6db..ba6596d1a2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.monitoring; -import java.net.URI; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.proxy.ProxyServlet; @@ -36,75 +30,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.net.URI; + public class EsGateway extends ProxyServlet { - private static final long serialVersionUID = 1L; - private static Logger log = LoggerFactory.getLogger(EsGateway.class.getName()); + private static final long serialVersionUID = 1L; + private static final Logger log = LoggerFactory.getLogger(EsGateway.class); - @Override - public URI rewriteURI(HttpServletRequest request) { + @Override + public URI rewriteURI(HttpServletRequest request) { - String originalUrl = request.getRequestURI(); + String originalUrl = request.getRequestURI(); - String redirectedUrl = getModifiedUrl(request); + String redirectedUrl = getModifiedUrl(request); - log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); - return URI.create(redirectedUrl); - } + log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl); + return URI.create(redirectedUrl); + } - @Override - public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) { - super.customizeProxyRequest(proxyRequest, request); + @Override + public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) { + super.customizeProxyRequest(proxyRequest, request); - } + } - @Override - protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) { - super.onResponseSuccess(request, response, proxyResponse); - } + @Override + protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) { + super.onResponseSuccess(request, response, proxyResponse); + } - public String getModifiedUrl(HttpServletRequest request) { - String esHost = null; - String esPort = null; - MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext()); - if (monitoringBL == null) { - log.error("failed to retrive monitoringBL."); - } else { - esHost = monitoringBL.getEsHost(); - esPort = monitoringBL.getEsPort(); - } + public String getModifiedUrl(HttpServletRequest request) { + String esHost = null; + String esPort = null; + MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext()); + if (monitoringBL == null) { + log.error("failed to retrive monitoringBL."); + } else { + esHost = monitoringBL.getEsHost(); + esPort = monitoringBL.getEsPort(); + } - //String scheme = request.getScheme(); esGateway HTTP - String scheme = "http"; - String contextPath = request.getContextPath(); // /mywebapp - String servletPath = request.getServletPath(); // /servlet/MyServlet - String pathInfo = request.getPathInfo(); // /a/b;c=123 - String queryString = request.getQueryString(); // d=789 + //String scheme = request.getScheme(); esGateway HTTP + String scheme = "http"; + String contextPath = request.getContextPath(); // /mywebapp + String servletPath = request.getServletPath(); // /servlet/MyServlet + String pathInfo = request.getPathInfo(); // /a/b;c=123 + String queryString = request.getQueryString(); // d=789 - StringBuilder url = new StringBuilder(); - url.append(scheme).append("://").append(esHost); - url.append(":").append(esPort); - url.append(contextPath).append(servletPath); + StringBuilder url = new StringBuilder(); + url.append(scheme).append("://").append(esHost); + url.append(":").append(esPort); + url.append(contextPath).append(servletPath); - if (pathInfo != null) { - url.append(pathInfo); - } - if (queryString != null) { - url.append("?").append(queryString); - } + if (pathInfo != null) { + url.append(pathInfo); + } + if (queryString != null) { + url.append("?").append(queryString); + } - String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/"); - return redirectedUrl; + String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/"); + return redirectedUrl; - } + } - protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { + protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class); - return monitoringBusinessLogic; - } + return monitoringBusinessLogic; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index 1625b50bae..b67469d469 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -20,30 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; -import java.util.zip.ZipInputStream; - -import javax.annotation.Resource; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; import org.openecomp.sdc.be.components.impl.ImportUtils; @@ -67,870 +51,830 @@ import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.UploadArtifactInfo; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.YamlToObjectConverter; import org.openecomp.sdc.common.util.ZipUtil; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; - -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.zip.ZipInputStream; public abstract class AbstractValidationsServlet extends BeGenericServlet { - @Resource - private ServletUtils servletUtils; - - @Resource - private ResourceImportManager resourceImportManager; - - @Autowired - protected ComponentsUtils componentsUtils; - - private Logger log = null; - - protected void init(Logger log) { - initLog(log); - initSpringFromContext(); - - } - - protected synchronized void initLog(Logger log) { - if (this.log == null) { - this.log = log; - } - } - - private synchronized void initSpringFromContext() { - if (servletUtils == null) { - ServletContext context = servletRequest.getSession().getServletContext(); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context - .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - servletUtils = webApplicationContext.getBean(ServletUtils.class); - resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); - } - } - - protected void validateResourceDoesNotExist(Wrapper responseWrapper, User user, String resourceName) { - if (resourceImportManager.isResourceExist(resourceName)) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validateUserExist(Wrapper responseWrapper, Wrapper userWrapper, String userUserId) { - log.debug("get user {} from DB", userUserId); - // get user details - if (userUserId == null) { - log.info("user userId is null"); - Response response = returnMissingInformation(new User()); - responseWrapper.setInnerElement(response); - } - - else { - IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); - Either eitherCreator = userAdmin.getUser(userUserId, false); - if (eitherCreator.isRight()) { - log.info("user is not listed. userId={}", userUserId); - User user = new User(); - user.setUserId(userUserId); - Response response = returnMissingInformation(user); - responseWrapper.setInnerElement(response); - } else { - userWrapper.setInnerElement(eitherCreator.left().value()); - } - } - } - - protected Response returnMissingInformation(User user) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - return buildErrorResponse(responseFormat); - } - - protected void validateDataNotNull(Wrapper responseWrapper, Object... dataParams) { - for (Object dataElement : dataParams) { - if (dataElement == null) { - log.info("Invalid body was received."); - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(response); - break; - } - } - - } - - protected void validateUserRole(Wrapper errorResponseWrapper, User user) { - log.debug("validate user role"); - if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) { - log.info("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - - Response response = buildErrorResponse(responseFormat); - errorResponseWrapper.setInnerElement(response); - } - - } - - protected void validateZip(Wrapper responseWrapper, File file, String payloadName) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) { - log.info("Invalid json was received. payloadName should be yml file name"); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResponse); - } - - } - protected void validateCsar(Wrapper responseWrapper, File file, String payloadName) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) { - log.info("Invalid json was received. payloadName should be yml file name"); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void fillZipContents(Wrapper yamlStringWrapper, File file) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - String ymlName = unzippedFolder.keySet().iterator().next(); - fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); - } - - protected void fillToscaTemplateFromZip(Wrapper yamlStringWrapper, String payloadName, File file) throws FileNotFoundException { - InputStream fileInputStream = new FileInputStream(file); - Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); - byte[] yamlFileInBytes = unzippedFolder.get(payloadName); - String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8); - log.debug("received yaml: {}", yamlAsString); - yamlStringWrapper.setInnerElement(yamlAsString); - } - - protected void fillPayloadDataFromFile(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) { - try(InputStream fileInputStream = new FileInputStream(file);){ - - byte [] data = new byte[(int)file.length()]; - if( fileInputStream.read(data) == -1){ - log.info("Invalid json was received."); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - String payloadData = Base64.encodeBase64String(data); - uploadResourceInfoWrapper.setPayloadData(payloadData); - - - - } catch (IOException e) { - log.info("Invalid json was received or Error while closing input Stream."); - log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - - } - } - - protected void validateUserRole(Wrapper errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) { - log.debug("validate user role"); - if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) { - if (!user.getRole().equals(Role.ADMIN.name())) { - log.info("user is not in appropriate role to perform action"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - log.debug("audit before sending response"); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - - Response response = buildErrorResponse(responseFormat); - errorResponseWrapper.setInnerElement(response); - } - } else { - validateUserRole(errorResponseWrapper, user); - } - - } - - protected void validateAndFillResourceJson(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) { - boolean isValid; - try { - log.debug("The received json is {}", resourceInfo); - UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class); - if (resourceInfoObject == null) { - isValid = false; - } else { - if (!resourceAuthorityEnum.isBackEndImport()) { - isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); - //only resource name is checked - } else { - isValid = true; - } - uploadResourceInfoWrapper.setInnerElement(resourceInfoObject); - } - - } catch (JsonSyntaxException e) { - log.debug("Invalid json was received. {}", e.getMessage(), e); - isValid = false; - - } - if (!isValid) { - log.info("Invalid json was received."); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null); - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - } - - protected void validateAuthorityType(Wrapper responseWrapper, String authorityType) { - log.debug("The received authority type is {}", authorityType); - ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType); - if (authorityTypeEnum == null) { - log.info("Invalid authority type was received."); - Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - responseWrapper.setInnerElement(errorResp); - } - } - - public ServletUtils getServletUtils() { - initSpringFromContext(); - return servletUtils; - } - - public Gson getGson() { - return getServletUtils().getGson(); - } - - public ComponentsUtils getComponentsUtils() { - return getServletUtils().getComponentsUtils(); - } - - protected void validatePayloadIsTosca(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { - log.debug("checking payload is valid tosca"); - boolean isValid; - Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - - if (findFirstToscaStringElement.isRight()) { - isValid = false; - } else { - String defenitionVersionFound = findFirstToscaStringElement.left().value(); - if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { - isValid = false; - } else { - isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); - } - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validatePayloadIsYml(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) { - log.debug("checking tosca template is valid yml"); - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes()); - if (!isYamlValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validatePayloadNameSpace(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) { - boolean isValid; - String nameSpace = ""; - Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { - isValid = false; - } else { - nameSpace = toscaElement.left().value().keySet().iterator().next(); - isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); - } - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } else { - String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); - String[] findTypes = str1.split("\\."); - if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) { - String type = findTypes[0].toUpperCase(); - resourceInfo.setResourceType(type); - } else { - resourceInfo.setResourceType(ResourceTypeEnum.VFC.name()); - } - } - - } - - protected void validatePayloadIsSingleResource(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { - log.debug("checking payload contains single resource"); - boolean isValid; - Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); - if (toscaElement.isRight()) { - isValid = false; - } else { - isValid = toscaElement.left().value().size() == 1; - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validatePayloadIsNotService(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { - log.debug("checking payload is not a tosca service"); - Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); - Either toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); - - if (toscaElement.isLeft()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validateToscaTemplatePayloadName(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { - String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName(); - boolean isValidSuffix = false; - if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) { - for (String validSuffix : ImportUtils.Constants.TOSCA_YML_CSAR_VALID_SUFFIX) { - isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix); - } - } - if (!isValidSuffix) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - - } - - protected void validateMD5(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) { - boolean isValid; - String recievedMD5 = request.getHeader(Constants.MD5_HEADER); - if (recievedMD5 == null) { - isValid = false; - } else { - String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString); - isValid = calculateMD5.equals(recievedMD5); - } - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void validateComponentType(Wrapper responseWrapper, Wrapper componentWrapper, String componentType) { - boolean isValid; - if (componentType == null) { - isValid = false; - } else { - if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) { - isValid = true; - componentWrapper.setInnerElement(ComponentTypeEnum.RESOURCE); - } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) { - isValid = true; - componentWrapper.setInnerElement(ComponentTypeEnum.SERVICE); - } else { - isValid = false; - } - } - if (!isValid) { - log.debug("Invalid componentType:{}", componentType); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - Response errorResp = buildErrorResponse(responseFormat); - responseWrapper.setInnerElement(errorResp); - } - } - - protected void fillToscaTemplateFromJson(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo resourceInfo) { - if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } else { - String toscaPayload = resourceInfo.getPayloadData(); - String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); - yamlStringWrapper.setInnerElement(decodedPayload); - } - - } - - protected void fillPayload(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, - File file) throws FileNotFoundException { - - if (responseWrapper.isEmpty()) { - if (resourceAuthorityEnum.isBackEndImport()) { - // PrePayload Validations - if (responseWrapper.isEmpty()) { - validateDataNotNull(responseWrapper, file, resourceInfoJsonString); - } - if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ - if (responseWrapper.isEmpty()) { - validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); - } - - // Fill PayLoad From File - if (responseWrapper.isEmpty()) { - fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); - } - }else{ - - if (responseWrapper.isEmpty()) { - validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); - } - - // Fill PayLoad From File - if (responseWrapper.isEmpty()) { - fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file); - } - - } - - } else { - // Fill PayLoad From JSON - if (responseWrapper.isEmpty()) { - fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement()); - } - } - - } - - } - - protected void specificResourceAuthorityValidations(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString, - ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException { - - if (responseWrapper.isEmpty()) { - // UI Only Validation - if (!resourceAuthorityEnum.isBackEndImport()) { - importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString); - } - - // User Defined Type Resources - if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { - if (responseWrapper.isEmpty()) { - validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); - } - - } - } - } - - protected void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId, - String resourceInfoJsonString) { - - if (responseWrapper.isEmpty()) { - validateUserExist(responseWrapper, userWrapper, userUserId); - } - - if (responseWrapper.isEmpty()) { - validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum); - } - - if (responseWrapper.isEmpty()) { - validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString); - } - - if (responseWrapper.isEmpty()) { - validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement(), resourceAuthorityEnum); - } - - } - - private void validateResourceType(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum) { - String resourceType = uploadResourceInfo.getResourceType(); - if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - if (resourceType.equals(ResourceTypeEnum.getTypeByName("VF").getValue()) && resourceAuthorityEnum == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE){ - log.debug("Import of VF resource type is forbidden - VF resource import can be done using onboarding flow only"); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_TYPE); - Response errorResponse = buildErrorResponse(responseFormat); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - responseWrapper.setInnerElement(errorResponse); - } - } - - protected void importUIValidations(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) { - if (responseWrapper.isEmpty()) { - validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString); - } - if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) { - validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName()); - } - } - - protected void commonPayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { - - if (responseWrapper.isEmpty()) { - validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - } - - /*protected void topologyTemplatePayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { - - if (responseWrapper.isEmpty()) { - validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); - } - if (responseWrapper.isEmpty()) { - validatePayloadIsTopologyTemplate(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); - } - - }*/ - - protected void handleImport(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { - Either, ResponseFormat> createOrUpdateResponse; - Response response; - Object representation = null; - - if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) { - log.debug("import resource from csar"); - - createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId); - //if (createOrUpdateResponse.isLeft()){ - // LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); - // lifecycleChangeInfo.setUserRemarks("certification on import"); - // Function> validator = (resource) -> resourceImportManager.getResourceBusinessLogic().validatePropertiesDefaultValues(createOrUpdateResponse.left().value().left); - //} - - } else if (!authority.isUserTypeResource()) { - log.debug("import normative type resource"); - createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); - } else { - log.debug("import user resource (not normative type)"); - createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false, false); - } - if (createOrUpdateResponse.isRight()) { - response = buildErrorResponse(createOrUpdateResponse.right().value()); - } else { - try { - representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft()); - } catch (IOException e) { - log.debug("Error while building resource representation : {}", e.getMessage(), e); - } - ActionStatus successStatus = createOrUpdateResponse.left().value().right; - response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation); - } - responseWrapper.setInnerElement(response); - } - - private Either, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { - - Either createOrUpdateResourceRes; - ImmutablePair result = null; - ActionStatus actionStatus; - org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); - String payloadName = resourceInfoObject.getPayloadName(); - fillResourceFromResourceInfoObject(resource, resourceInfoObject); - - Either, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject); - if (csarUIPayloadRes.isRight()) { - return Either.right(csarUIPayloadRes.right().value()); - } - Map csarUIPayload = csarUIPayloadRes.left().value(); - - createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { - createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - actionStatus = ActionStatus.CREATED; - } else { - createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); - if (createOrUpdateResourceRes.isRight()) { - return Either.right(createOrUpdateResourceRes.right().value()); - } - actionStatus = ActionStatus.OK; - } - result = new ImmutablePair(createOrUpdateResourceRes.left().value(), actionStatus); - return Either.left(result); - } - - private Either getAndValidateCsarYaml(Map csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) { - - Either, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils()); - - if (getToscaYamlRes.isRight()) { - ResponseFormat responseFormat = getToscaYamlRes.right().value(); - log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); - BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); - getComponentsUtils().auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null); - return Either.right(responseFormat); - } - String toscaYaml = getToscaYamlRes.left().value().getValue(); - - log.debug("checking tosca template is valid yml"); - YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); - boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes()); - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - return Either.right(responseFormat); - } - - log.debug("checking payload is valid tosca"); - String heatDecodedPayload = toscaYaml; - Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); - Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); - - if (findFirstToscaStringElement.isRight()) { - isValid = false; - } else { - String defenitionVersionFound = findFirstToscaStringElement.left().value(); - if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { - isValid = false; - } else { - isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); - } - } - - if (!isValid) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); - EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class); - additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName()); - getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam); - return Either.right(responseFormat); - } - return Either.left(resource); - } - - private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { - if (resource != null && resourceInfoObject != null) { - resource.setDescription(resourceInfoObject.getDescription()); - resource.setTags(resourceInfoObject.getTags()); - resource.setCategories(resourceInfoObject.getCategories()); - resource.setContactId(resourceInfoObject.getContactId()); - resource.setName(resourceInfoObject.getName()); - resource.setIcon(resourceInfoObject.getResourceIconPath()); - resource.setVendorName(resourceInfoObject.getVendorName()); - resource.setVendorRelease(resourceInfoObject.getVendorRelease()); - resource.setResourceType(ResourceTypeEnum.valueOf(resourceInfoObject.getResourceType())); - List artifactList = resourceInfoObject.getArtifactList(); - if (artifactList != null) { - Map artifactsHM = new HashMap(); - for (UploadArtifactInfo artifact : artifactList) { - ArtifactDefinition artifactDef = new ArtifactDefinition(); - artifactDef.setArtifactName(artifact.getArtifactName()); - artifactDef.setArtifactType(artifact.getArtifactType().getType()); - artifactDef.setDescription(artifact.getArtifactDescription()); - artifactDef.setPayloadData(artifact.getArtifactData()); - artifactDef.setArtifactRef(artifact.getArtifactPath()); - artifactsHM.put(artifactDef.getArtifactName(), artifactDef); - } - resource.setArtifacts(artifactsHM); - } - } - - } - - private Either, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) { - String csarUUID = innerElement.getPayloadName(); - String payloadData = innerElement.getPayloadData(); - if (payloadData == null) { - log.info("Failed to decode received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); - } - - byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)); - if (decodedPayload == null) { - log.info("Failed to decode received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); - } - - Map csar = ZipUtil.readZip(decodedPayload); - if (csar == null) { - log.info("Failed to unzip received csar", csarUUID); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); - } - return Either.left(csar); - } - - protected void validateInputStream(final HttpServletRequest request, Wrapper dataWrapper, Wrapper errorWrapper) throws IOException { - InputStream inputStream = request.getInputStream(); - byte[] bytes = IOUtils.toByteArray(inputStream); - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8)); - } - - } - - protected void validateClassParse(String data, Wrapper parsedClassWrapper, Supplier> classGen, Wrapper errorWrapper) { - try { - T parsedClass = gson.fromJson(data, classGen.get()); - if (parsedClass == null) { - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } else { - parsedClassWrapper.setInnerElement(parsedClass); - } - } catch (JsonSyntaxException e) { - log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - } - - protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper blWrapper, Wrapper errorWrapper) { - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } else { - blWrapper.setInnerElement(componentInstanceLogic); - } - } - - protected Response buildResponseFromElement(Wrapper errorWrapper, Wrapper attributeWrapper) throws IOException { - Response response; - if (errorWrapper.isEmpty()) { - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(attributeWrapper.getInnerElement()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } else { - response = buildErrorResponse(errorWrapper.getInnerElement()); - } - return response; - } - - protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper responseWrapper) { - ResponseFormat responseFormat; - if(StringUtils.isEmpty(instanceIdHeader) ){ - log.debug("Missing X-ECOMP-InstanceID header"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); - responseWrapper.setInnerElement(responseFormat); - } - } - - protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { - ResponseFormat responseFormat; - if( StringUtils.isEmpty(header)){ - log.debug("MissingUSER_ID"); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); - responseWrapper.setInnerElement(responseFormat); - } - } - - /** - * Convert json to Object object - * @param - * @param classSupplier - * @param json - * @return - */ - public Either parseToObject(String json, Supplier> classSupplier) { - - try { - T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); - return Either.left(object); - } catch (Exception e) { - log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } - - /** - * Convert json to Object object - * @param - * @param json - * @param type - * @return - */ - public Either, ResponseFormat> parseListOfObjects(String json, Type type) { - try { - List listOfObjects = gson.fromJson(json, type); - return Either.left(listOfObjects); - } catch (Exception e) { - log.debug("Failed to parse json to {} object", type.getClass().getName(), e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return Either.right(responseFormat); - } - } + private static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_"; + private static final List TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1"); + private static final List TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar"); + + protected ServletUtils servletUtils; + + protected ResourceImportManager resourceImportManager; + + protected ComponentsUtils componentsUtils; + + private Logger log = null; + + protected void init(Logger log) { + initLog(log); + initSpringFromContext(); + + } + + protected synchronized void initLog(Logger log) { + if (this.log == null) { + this.log = log; + } + } + + private synchronized void initSpringFromContext() { + if (servletUtils == null) { + ServletContext context = servletRequest.getSession().getServletContext(); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + servletUtils = webApplicationContext.getBean(ServletUtils.class); + resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); + } + } + + protected void validateResourceDoesNotExist(Wrapper responseWrapper, User user, String resourceName) { + if (resourceImportManager.isResourceExist(resourceName)) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceName, AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validateUserExist(Wrapper responseWrapper, Wrapper userWrapper, String userUserId) { + log.debug("get user {} from DB", userUserId); + // get user details + if (userUserId == null) { + log.info("user userId is null"); + Response response = returnMissingInformation(new User()); + responseWrapper.setInnerElement(response); + } + + else { + IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin(); + Either eitherCreator = userAdmin.getUser(userUserId, false); + if (eitherCreator.isRight()) { + log.info("user is not listed. userId={}", userUserId); + User user = new User(); + user.setUserId(userUserId); + Response response = returnMissingInformation(user); + responseWrapper.setInnerElement(response); + } else { + userWrapper.setInnerElement(eitherCreator.left().value()); + } + } + } + + protected Response returnMissingInformation(User user) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + return buildErrorResponse(responseFormat); + } + + protected void validateDataNotNull(Wrapper responseWrapper, Object... dataParams) { + for (Object dataElement : dataParams) { + if (dataElement == null) { + log.info("Invalid body was received."); + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(response); + break; + } + } + + } + + protected void validateUserRole(Wrapper errorResponseWrapper, User user) { + log.debug("validate user role"); + if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) { + log.info("user is not in appropriate role to perform action"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + + Response response = buildErrorResponse(responseFormat); + errorResponseWrapper.setInnerElement(response); + } + + } + + protected void validateZip(Wrapper responseWrapper, File file, String payloadName) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) { + log.info("Invalid json was received. payloadName should be yml file name"); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResponse); + } + + } + protected void validateCsar(Wrapper responseWrapper, File file, String payloadName) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) { + log.info("Invalid json was received. payloadName should be yml file name"); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void fillZipContents(Wrapper yamlStringWrapper, File file) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + String ymlName = unzippedFolder.keySet().iterator().next(); + fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file); + } + + protected void fillToscaTemplateFromZip(Wrapper yamlStringWrapper, String payloadName, File file) throws FileNotFoundException { + InputStream fileInputStream = new FileInputStream(file); + Map unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream)); + byte[] yamlFileInBytes = unzippedFolder.get(payloadName); + String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8); + log.debug("received yaml: {}", yamlAsString); + yamlStringWrapper.setInnerElement(yamlAsString); + } + + protected void fillPayloadDataFromFile(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) { + try(InputStream fileInputStream = new FileInputStream(file)){ + + byte [] data = new byte[(int)file.length()]; + if( fileInputStream.read(data) == -1){ + log.info("Invalid json was received."); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + } + String payloadData = Base64.encodeBase64String(data); + uploadResourceInfoWrapper.setPayloadData(payloadData); + + + + } catch (IOException e) { + log.info("Invalid json was received or Error while closing input Stream."); + log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + + } + } + + protected void validateUserRole(Wrapper errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) { + log.debug("validate user role"); + if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) { + if (!user.getRole().equals(Role.ADMIN.name())) { + log.info("user is not in appropriate role to perform action"); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + log.debug("audit before sending response"); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + + Response response = buildErrorResponse(responseFormat); + errorResponseWrapper.setInnerElement(response); + } + } else { + validateUserRole(errorResponseWrapper, user); + } + + } + + protected void validateAndFillResourceJson(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) { + boolean isValid; + try { + log.debug("The received json is {}", resourceInfo); + UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class); + if (resourceInfoObject == null) { + isValid = false; + } else { + if (!resourceAuthorityEnum.isBackEndImport()) { + isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); + //only resource name is checked + } else { + isValid = true; + } + uploadResourceInfoWrapper.setInnerElement(resourceInfoObject); + } + + } catch (JsonSyntaxException e) { + log.debug("Invalid json was received. {}", e.getMessage(), e); + isValid = false; + + } + if (!isValid) { + log.info("Invalid json was received."); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE); + Response errorResp = buildErrorResponse(responseFormat); + responseWrapper.setInnerElement(errorResp); + } + } + + protected void validateAuthorityType(Wrapper responseWrapper, String authorityType) { + log.debug("The received authority type is {}", authorityType); + ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType); + if (authorityTypeEnum == null) { + log.info("Invalid authority type was received."); + Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + responseWrapper.setInnerElement(errorResp); + } + } + + public ServletUtils getServletUtils() { + initSpringFromContext(); + return servletUtils; + } + + public Gson getGson() { + return getServletUtils().getGson(); + } + + public ComponentsUtils getComponentsUtils() { + return getServletUtils().getComponentsUtils(); + } + + protected void validatePayloadIsTosca(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { + log.debug("checking payload is valid tosca"); + boolean isValid; + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); + Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); + + if (findFirstToscaStringElement.isRight()) { + isValid = false; + } else { + String defenitionVersionFound = findFirstToscaStringElement.left().value(); + if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { + isValid = false; + } else { + isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); + } + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validatePayloadIsYml(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) { + log.debug("checking tosca template is valid yml"); + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes()); + if (!isYamlValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validatePayloadNameSpace(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) { + boolean isValid; + String nameSpace = ""; + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); + Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isRight() || toscaElement.left().value().size() != 1) { + isValid = false; + } else { + nameSpace = toscaElement.left().value().keySet().iterator().next(); + isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX); + } + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } else { + String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length()); + String[] findTypes = str1.split("\\."); + if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) { + String type = findTypes[0].toUpperCase(); + resourceInfo.setResourceType(type); + } else { + resourceInfo.setResourceType(ResourceTypeEnum.VFC.name()); + } + } + + } + + protected void validatePayloadIsSingleResource(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) { + log.debug("checking payload contains single resource"); + boolean isValid; + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); + Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES); + if (toscaElement.isRight()) { + isValid = false; + } else { + isValid = toscaElement.left().value().size() == 1; + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validatePayloadIsNotService(Wrapper responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) { + log.debug("checking payload is not a tosca service"); + Map mappedToscaTemplate = (Map) new Yaml().load(toscaPayload); + Either toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL); + + if (toscaElement.isLeft()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validateToscaTemplatePayloadName(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { + String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName(); + boolean isValidSuffix = false; + if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) { + for (String validSuffix : TOSCA_YML_CSAR_VALID_SUFFIX) { + isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix); + } + } + if (!isValidSuffix) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + + } + + protected void validateMD5(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) { + boolean isValid; + String recievedMD5 = request.getHeader(Constants.MD5_HEADER); + if (recievedMD5 == null) { + isValid = false; + } else { + String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString); + isValid = calculateMD5.equals(recievedMD5); + } + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void validateComponentType(Wrapper responseWrapper, Wrapper componentTypeWrapper, String componentType) { + boolean isValid; + if (componentType == null) { + isValid = false; + } else { + if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) { + isValid = true; + componentTypeWrapper.setInnerElement(ComponentTypeEnum.RESOURCE); + } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) { + isValid = true; + componentTypeWrapper.setInnerElement(ComponentTypeEnum.SERVICE); + } else { + isValid = false; + } + } + if (!isValid) { + log.debug("Invalid componentType:{}", componentType); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType))); + } + } + + protected Either convertToComponentType(String componentType) { + Wrapper errorWrapper = new Wrapper<>(); + Wrapper componentWrapper = new Wrapper<>(); + validateComponentType(errorWrapper, componentWrapper, componentType); + return errorWrapper.isEmpty() ? Either.left(componentWrapper.getInnerElement()) : Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + protected void fillToscaTemplateFromJson(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo resourceInfo) { + if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } else { + String toscaPayload = resourceInfo.getPayloadData(); + String decodedPayload = new String(Base64.decodeBase64(toscaPayload)); + yamlStringWrapper.setInnerElement(decodedPayload); + } + + } + + protected void fillPayload(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, + File file) throws FileNotFoundException { + + if (responseWrapper.isEmpty()) { + if (resourceAuthorityEnum.isBackEndImport()) { + // PrePayload Validations + if (responseWrapper.isEmpty()) { + validateDataNotNull(responseWrapper, file, resourceInfoJsonString); + } + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + if (responseWrapper.isEmpty()) { + validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file); + } + }else{ + + if (responseWrapper.isEmpty()) { + validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName()); + } + + // Fill PayLoad From File + if (responseWrapper.isEmpty()) { + fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file); + } + + } + + } else { + // Fill PayLoad From JSON + if (responseWrapper.isEmpty()) { + fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement()); + } + } + + } + + } + + protected void specificResourceAuthorityValidations(Wrapper responseWrapper, Wrapper uploadResourceInfoWrapper, Wrapper yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString, + ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException { + + if (responseWrapper.isEmpty()) { + // UI Only Validation + if (!resourceAuthorityEnum.isBackEndImport()) { + importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString); + } + + // User Defined Type Resources + if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { + if (responseWrapper.isEmpty()) { + validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement()); + } + + } + } + } + + protected void commonGeneralValidations(Wrapper responseWrapper, Wrapper userWrapper, Wrapper uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId, + String resourceInfoJsonString) { + + if (responseWrapper.isEmpty()) { + validateUserExist(responseWrapper, userWrapper, userUserId); + } + + if (responseWrapper.isEmpty()) { + validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum); + } + + if (responseWrapper.isEmpty()) { + validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString); + } + + if (responseWrapper.isEmpty()) { + validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement()); + } + + } + + private void validateResourceType(Wrapper responseWrapper, UploadResourceInfo uploadResourceInfo, User user) { + String resourceType = uploadResourceInfo.getResourceType(); + if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + Response errorResponse = buildErrorResponse(responseFormat); + getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE); + responseWrapper.setInnerElement(errorResponse); + } + } + + protected void importUIValidations(Wrapper responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) { + if (responseWrapper.isEmpty()) { + validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString); + } + if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) { + validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName()); + } + } + + protected void commonPayloadValidations(Wrapper responseWrapper, Wrapper yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) { + + if (responseWrapper.isEmpty()) { + validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement()); + } + if (responseWrapper.isEmpty()) { + validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement()); + } + } + + + protected void handleImport(Wrapper responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) { + Either, ResponseFormat> createOrUpdateResponse; + Response response; + Object representation = null; + + if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) { + log.debug("import resource from csar"); + + createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId); + } else if (!authority.isUserTypeResource()) { + log.debug("import normative type resource"); + createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true); + } else { + log.debug("import user resource (not normative type)"); + createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false); + } + if (createOrUpdateResponse.isRight()) { + response = buildErrorResponse(createOrUpdateResponse.right().value()); + } else { + try { + representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft()); + } catch (IOException e) { + log.debug("Error while building resource representation : {}", e.getMessage(), e); + } + ActionStatus successStatus = createOrUpdateResponse.left().value().right; + response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation); + } + responseWrapper.setInnerElement(response); + } + + private Either, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) { + + Either createOrUpdateResourceRes; + ImmutablePair result = null; + ActionStatus actionStatus; + org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); + String payloadName = resourceInfoObject.getPayloadName(); + fillResourceFromResourceInfoObject(resource, resourceInfoObject); + + Either, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject); + if (csarUIPayloadRes.isRight()) { + return Either.right(csarUIPayloadRes.right().value()); + } + Map csarUIPayload = csarUIPayloadRes.left().value(); + + createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + if (resourceUniqueId == null || resourceUniqueId.isEmpty()) { + createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + actionStatus = ActionStatus.CREATED; + } else { + createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId); + if (createOrUpdateResourceRes.isRight()) { + return Either.right(createOrUpdateResourceRes.right().value()); + } + actionStatus = ActionStatus.OK; + } + result = new ImmutablePair(createOrUpdateResourceRes.left().value(), actionStatus); + return Either.left(result); + } + + private Either getAndValidateCsarYaml(Map csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) { + + Either, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils()); + + if (getToscaYamlRes.isRight()) { + ResponseFormat responseFormat = getToscaYamlRes.right().value(); + log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed"); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE); + return Either.right(responseFormat); + } + String toscaYaml = getToscaYamlRes.left().value().getValue(); + + log.debug("checking tosca template is valid yml"); + YamlToObjectConverter yamlConvertor = new YamlToObjectConverter(); + boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes()); + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + + log.debug("checking payload is valid tosca"); + String heatDecodedPayload = toscaYaml; + Map mappedToscaTemplate = (Map) new Yaml().load(heatDecodedPayload); + Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION); + + if (findFirstToscaStringElement.isRight()) { + isValid = false; + } else { + String defenitionVersionFound = findFirstToscaStringElement.left().value(); + if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) { + isValid = false; + } else { + isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound); + } + } + + if (!isValid) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE); + getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + return Either.right(responseFormat); + } + return Either.left(resource); + } + + private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { + resourceImportManager.populateResourceMetadata(resourceInfoObject, resource); + fillArtifacts(resource, resourceInfoObject); + + } + + private void fillArtifacts(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) { + if (resource != null && resourceInfoObject != null) { + List artifactList = resourceInfoObject.getArtifactList(); + if (artifactList != null) { + Map artifactsHM = new HashMap(); + for (UploadArtifactInfo artifact : artifactList) { + ArtifactDefinition artifactDef = new ArtifactDefinition(); + artifactDef.setArtifactName(artifact.getArtifactName()); + artifactDef.setArtifactType(artifact.getArtifactType().getType()); + artifactDef.setDescription(artifact.getArtifactDescription()); + artifactDef.setPayloadData(artifact.getArtifactData()); + artifactDef.setArtifactRef(artifact.getArtifactPath()); + artifactsHM.put(artifactDef.getArtifactName(), artifactDef); + } + resource.setArtifacts(artifactsHM); + } + } + } + + private Either, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) { + String csarUUID = innerElement.getPayloadName(); + String payloadData = innerElement.getPayloadData(); + if (payloadData == null) { + log.info("Failed to decode received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); + } + + byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8)); + if (decodedPayload == null) { + log.info("Failed to decode received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID)); + } + + Map csar = ZipUtil.readZip(decodedPayload); + if (csar == null) { + log.info("Failed to unzip received csar", csarUUID); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); + } + return Either.left(csar); + } + + protected void validateInputStream(final HttpServletRequest request, Wrapper dataWrapper, Wrapper errorWrapper) throws IOException { + InputStream inputStream = request.getInputStream(); + byte[] bytes = IOUtils.toByteArray(inputStream); + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8)); + } + + } + + protected void validateClassParse(String data, Wrapper parsedClassWrapper, Supplier> classGen, Wrapper errorWrapper) { + try { + T parsedClass = gson.fromJson(data, classGen.get()); + if (parsedClass == null) { + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } else { + parsedClassWrapper.setInnerElement(parsedClass); + } + } catch (JsonSyntaxException e) { + log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + } + + protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper blWrapper, Wrapper errorWrapper) { + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } else { + blWrapper.setInnerElement(componentInstanceLogic); + } + } + + protected Response buildResponseFromElement(Wrapper errorWrapper, Wrapper attributeWrapper) throws IOException { + Response response; + if (errorWrapper.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(attributeWrapper.getInnerElement()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } else { + response = buildErrorResponse(errorWrapper.getInnerElement()); + } + return response; + } + + protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper responseWrapper) { + ResponseFormat responseFormat; + if(StringUtils.isEmpty(instanceIdHeader) ){ + log.debug("Missing X-ECOMP-InstanceID header"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + protected void validateHttpCspUserIdHeader(String header, Wrapper responseWrapper) { + ResponseFormat responseFormat; + if( StringUtils.isEmpty(header)){ + log.debug("MissingUSER_ID"); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID); + responseWrapper.setInnerElement(responseFormat); + } + } + + /** + * Convert json to Object object + * @param + * @param classSupplier + * @param json + * @return + */ + public Either parseToObject(String json, Supplier> classSupplier) { + + try { + T object = RepresentationUtils.fromRepresentation(json, classSupplier.get()); + return Either.left(object); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } + + /** + * Convert json to Object object + * @param + * @param json + * @param type + * @return + */ + public Either, ResponseFormat> parseListOfObjects(String json, Type type) { + try { + List listOfObjects = gson.fromJson(json, type); + return Either.left(listOfObjects); + } catch (Exception e) { + log.debug("Failed to parse json to {} object", type.getClass().getName(), e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return Either.right(responseFormat); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java index ae103dbaca..f6d89e9065 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java @@ -20,22 +20,9 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,503 +37,496 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Additional Information Servlet", description = "Additional Information Servlet") @Singleton public class AdditionalInformationServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class.getName()); - - /** - * - * @param resourceId - * @param data - * @param request - * @param userUserId - * @return - */ - @POST - @Path("/resources/{resourceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data); - - } - - /** - * - * @param serviceId - * @param data - * @param request - * @param userUserId - * @return - */ - @POST - @Path("/services/{serviceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { - - return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data); - - } - - /** - * - * @param resourceId - * @param labelId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data); - - } - - /** - * - * @param serviceId - * @param labelId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data); - - } - - /** - * - * @param resourceId - * @param labelId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); - - } - - /** - * - * @param serviceId - * @param labelId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); - - } - - /** - * - * @param resourceId - * @param labelId - * @param request - * @param userId - * @return - */ - @GET - @Path("/resources/{resourceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); - - } - - /** - * - * @param serviceId - * @param labelId - * @param request - * @param userId - * @return - */ - @GET - @Path("/services/{serviceId}/additionalinfo/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, - @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); - - } - - /** - * - * @param resourceId - * @param request - * @param userId - * @return - */ - @GET - @Path("/resources/{resourceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId); - - } - - /** - * - * @param serviceId - * @param request - * @param userId - * @return - */ - @GET - @Path("/services/{serviceId}/additionalinfo") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Additional information key already exist") }) - public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId); - - } - - /** - * - * Create additional information property under given resource/service - * - * @param nodeType - * @param uniqueId - * @param request - * @param userId - * @param data - * @return - */ - protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); - - try { - // convert json to AdditionalInfoParameterInfo - AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); - - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); - - Either either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat); - return buildErrorResponse(responseFormat); - } - - AdditionalInfoParameterInfo createdAI = either.left().value(); - - log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createdAI); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Additional Information"); - log.debug("Create additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - - } - - /** - * Update additional information property by id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @param data - * @return - */ - protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - log.debug("data is {}", data); - - try { - // convert json to AdditionalInfoParameterInfo - AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); - - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); - - additionalInfoParameterInfo.setUniqueId(labelId); - - Either either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } - - AdditionalInfoParameterInfo createdAI = either.left().value(); - - log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + private static final Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class); + + /** + * + * @param resourceId + * @param data + * @param request + * @param userUserId + * @return + */ + @POST + @Path("/resources/{resourceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { + + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data); + + } + + /** + * + * @param serviceId + * @param data + * @param request + * @param userUserId + * @return + */ + @POST + @Path("/services/{serviceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) { + + return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data); + + } + + /** + * + * @param resourceId + * @param labelId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data); + + } + + /** + * + * @param serviceId + * @param labelId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data); + + } + + /** + * + * @param resourceId + * @param labelId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); + + } + + /** + * + * @param serviceId + * @param labelId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); + + } + + /** + * + * @param resourceId + * @param labelId + * @param request + * @param userId + * @return + */ + @GET + @Path("/resources/{resourceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId); + + } + + /** + * + * @param serviceId + * @param labelId + * @param request + * @param userId + * @return + */ + @GET + @Path("/services/{serviceId}/additionalinfo/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId); + + } + + /** + * + * @param resourceId + * @param request + * @param userId + * @return + */ + @GET + @Path("/resources/{resourceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId); + + } + + /** + * + * @param serviceId + * @param request + * @param userId + * @return + */ + @GET + @Path("/services/{serviceId}/additionalinfo") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Additional information key already exist") }) + public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId); + + } + + /** + * + * Create additional information property under given resource/service + * + * @param nodeType + * @param uniqueId + * @param request + * @param userId + * @param data + * @return + */ + protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + log.debug("data is {}", data); + + try { + // convert json to AdditionalInfoParameterInfo + AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); + + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); + + Either either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat); + return buildErrorResponse(responseFormat); + } + + AdditionalInfoParameterInfo createdAI = either.left().value(); + + log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createdAI); + + } catch (Exception e) { + log.debug("Create additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + + } + + /** + * Update additional information property by id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @param data + * @return + */ + protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + log.debug("data is {}", data); + + try { + // convert json to AdditionalInfoParameterInfo + AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class); + + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); + + additionalInfoParameterInfo.setUniqueId(labelId); + + Either either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } + + AdditionalInfoParameterInfo createdAI = either.left().value(); + + log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information"); - log.debug("Update additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information"); + log.debug("Update additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * - * Delete an additional information property by id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @return - */ - protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { + /** + * + * Delete an additional information property by id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @return + */ + protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - AdditionalInformationBusinessLogic businessLogic = getBL(context); + AdditionalInformationBusinessLogic businessLogic = getBL(context); - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setUniqueId(labelId); + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setUniqueId(labelId); - Either either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + Either either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInfoParameterInfo createdAI = either.left().value(); + AdditionalInfoParameterInfo createdAI = either.left().value(); - log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information"); - log.debug("Delete additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information"); + log.debug("Delete additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * Get a specific additional information property by a given id under given resource/service - * - * @param nodeType - * @param uniqueId - * @param labelId - * @param request - * @param userId - * @return - */ - protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { + /** + * Get a specific additional information property by a given id under given resource/service + * + * @param nodeType + * @param uniqueId + * @param labelId + * @param request + * @param userId + * @return + */ + protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - // create the new property - AdditionalInformationBusinessLogic businessLogic = getBL(context); + // create the new property + AdditionalInformationBusinessLogic businessLogic = getBL(context); - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); - additionalInfoParameterInfo.setUniqueId(labelId); + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(); + additionalInfoParameterInfo.setUniqueId(labelId); - Either either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); + Either either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInfoParameterInfo createdAI = either.left().value(); + AdditionalInfoParameterInfo createdAI = either.left().value(); - log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); + log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, createdAI); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, createdAI); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information"); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information"); - log.debug("get additional information failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + log.debug("get additional information failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - /** - * Get all additional information properties under given resource/service - * - * @param nodeType - * @param uniqueId - * @param request - * @param userId - * @return - */ - protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) { + /** + * Get all additional information properties under given resource/service + * + * @param nodeType + * @param uniqueId + * @param request + * @param userId + * @return + */ + protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); - try { + try { - AdditionalInformationBusinessLogic businessLogic = getBL(context); + AdditionalInformationBusinessLogic businessLogic = getBL(context); - Either either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId); - if (either.isRight()) { - ResponseFormat responseFormat = either.right().value(); - log.info("Failed to update additional information property. Reason - {}", responseFormat); - return buildErrorResponse(responseFormat); - } + Either either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId); + if (either.isRight()) { + ResponseFormat responseFormat = either.right().value(); + log.info("Failed to update additional information property. Reason - {}", responseFormat); + return buildErrorResponse(responseFormat); + } - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition); + log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, additionalInformationDefinition); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, additionalInformationDefinition); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Additional Information"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information"); - log.debug("Get all addiotanl information properties failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information"); + log.debug("Get all addiotanl information properties failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } - } + } - private AdditionalInformationBusinessLogic getBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class); - return bl; - } + private AdditionalInformationBusinessLogic getBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class); + return bl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java index 5a26b7c4e6..fa7ed4b547 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java @@ -20,23 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; @@ -52,15 +42,21 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; /** * Root resource (exposed at "/" path) */ @@ -70,535 +66,535 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ArtifactServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName()); - - // *************** Resources - @POST - @Path("/resources/{resourceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact"); - log.debug("loadArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact"); - log.debug("updateArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null); - } catch (Exception e) { - log.debug("deleteArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Services - @POST - @Path("/services/{serviceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact"); - log.debug("loadInformationArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact"); - log.debug("updateInformationArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Services api artifacts - @POST - @Path("/services/{serviceId}/artifacts/api/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact"); - log.debug("updateApiArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/services/{serviceId}/artifacts/api/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact"); - log.debug("deleteApiArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact"); - log.debug("deleteInformationalArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /* - * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href) - */ - - @GET - @Path("/services/{serviceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") }) - public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); - log.debug("downloadServiceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/resources/{resourceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); - log.debug("downloadResourceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") }) - public Response downloadResourceInstanceArtifactBase64( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - // *************** Resource lifecycle ( interfces ) - - @POST - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Create, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); - log.debug("loadArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface"); - log.debug("deleteArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Artifact already exist") }) - public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request, - @ApiParam(value = "json describe the artifact", required = true) String data) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Update, null, null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); - log.debug("updateArtifactToInterface unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateRIArtifact( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); - log.debug("updateRIArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType); - } catch (Exception e) { - log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Create, componentId, containerComponentType); - } catch (Exception e) { - log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, - @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); - } catch (Exception e) { - log.debug("deleteArtifact unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @GET - @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response getComponentArtifacts( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) - public Response getComponentInstanceArtifacts( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - try { - return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); - log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - // ////////// API END /////////////////////////// - - // ************ private ********************* - - private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.Create); - } - - private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { - return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update); - } - - private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); - - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - byte[] file = actionResult.left().value().getRight(); - String base64Contents = new String(Base64.encodeBase64(file)); - String artifactName = actionResult.left().value().getLeft(); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData(); - artifactUiDownloadData.setArtifactName(artifactName); - artifactUiDownloadData.setBase64Contents(base64Contents); - response = buildOkResponse(responseFormat, artifactUiDownloadData); - } - return response; - } - - private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE; - Either, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); - - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value()); - } - - return response; - } - - - private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { - return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null); - } - - private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) { - String userId = request.getHeader(Constants.USER_ID_HEADER); - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.Delete), artifactId, null, null, null, interfaceType, operationName, - parentId, null); - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - Either result = actionResult.left().value(); - if (result.isLeft()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); - } - } - return response; - - } - - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, - String containerComponentType) { - ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); - String origMd5 = request.getHeader(Constants.MD5_HEADER); - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ServletContext context = request.getSession().getServletContext(); - ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); - Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, - artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, - containerComponentType); - Response response; - if (actionResult.isRight()) { - response = buildErrorResponse(actionResult.right().value()); - } else { - Either result = actionResult.left().value(); - if (result.isLeft()) { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); - } - } - return response; - - } - - private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { - return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null); - } + private static final Logger log = LoggerFactory.getLogger(ArtifactServlet.class); + + // *************** Resources + @POST + @Path("/resources/{resourceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact"); + log.debug("loadArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact"); + log.debug("updateArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null); + } catch (Exception e) { + log.debug("deleteArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Services + @POST + @Path("/services/{serviceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact"); + log.debug("loadInformationArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact"); + log.debug("updateInformationArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Services api artifacts + @POST + @Path("/services/{serviceId}/artifacts/api/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact"); + log.debug("updateApiArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/services/{serviceId}/artifacts/api/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @HeaderParam(value = Constants.MD5_HEADER) String origMd5) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact"); + log.debug("deleteApiArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact"); + log.debug("deleteInformationalArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /* + * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href) + */ + + @GET + @Path("/services/{serviceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") }) + public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64"); + log.debug("downloadServiceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/resources/{resourceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64"); + log.debug("downloadResourceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") }) + public Response downloadResourceInstanceArtifactBase64( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + // *************** Resource lifecycle ( interfces ) + + @POST + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface"); + log.debug("loadArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface"); + log.debug("deleteArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Artifact already exist") }) + public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request, + @ApiParam(value = "json describe the artifact", required = true) String data) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface"); + log.debug("updateArtifactToInterface unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateRIArtifact( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact"); + log.debug("updateRIArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType); + } catch (Exception e) { + log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType); + } catch (Exception e) { + log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, + @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId); + } catch (Exception e) { + log.debug("deleteArtifact unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @GET + @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") }) + public Response getComponentInstanceArtifacts( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + try { + return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64"); + log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + // ////////// API END /////////////////////////// + + // ************ private ********************* + + private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) { + return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.CREATE); + } + + private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) { + return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE); + } + + private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType); + + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + byte[] file = actionResult.left().value().getRight(); + String base64Contents = new String(Base64.encodeBase64(file)); + String artifactName = actionResult.left().value().getLeft(); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData(); + artifactUiDownloadData.setArtifactName(artifactName); + artifactUiDownloadData.setBase64Contents(base64Contents); + response = buildOkResponse(responseFormat, artifactUiDownloadData); + } + return response; + } + + private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE; + Either, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId); + + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value()); + } + + return response; + } + + + private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) { + return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null); + } + + private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) { + String userId = request.getHeader(Constants.USER_ID_HEADER); + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName, + parentId, null); + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + Either result = actionResult.left().value(); + if (result.isLeft()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); + } + } + return response; + + } + + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId, + String containerComponentType) { + ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class); + String origMd5 = request.getHeader(Constants.MD5_HEADER); + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ServletContext context = request.getSession().getServletContext(); + ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); + Either, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, + artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId, + containerComponentType); + Response response; + if (actionResult.isRight()) { + response = buildErrorResponse(actionResult.right().value()); + } else { + Either result = actionResult.left().value(); + if (result.isLeft()) { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value()); + } + } + return response; + + } + + private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) { + return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index 1b02e0afa4..09ebb1cd31 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -20,21 +20,11 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -46,17 +36,13 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * Web Servlet for actions on Attributes * @@ -68,209 +54,209 @@ import io.swagger.annotations.ApiResponses; @Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet") @Singleton public class AttributeServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(AttributeServlet.class.getName()); - - /** - * Creates new Attribute on a resource with given resource ID - * - * @param resourceId - * @param data - * @param request - * @param userId - * @return - */ - @POST - @Path("resources/{resourceId}/attributes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource attribute already exist") }) - public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - - try { - Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); - // convert json to AttributeDefinition - - buildAttributeFromString(data, attributesWrapper, errorWrapper); - if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); - if (createAttribute.isRight()) { - errorWrapper.setInnerElement(createAttribute.right().value()); - } else { - attributesWrapper.setInnerElement(createAttribute.left().value()); - } - } - - Response response; - if (!errorWrapper.isEmpty()) { - log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); - } else { - PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); - log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); - log.debug("create property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - /** - * Updates existing Attribute with given attributeID on a resource with given resourceID - * - * @param resourceId - * @param attributeId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("resources/{resourceId}/attributes/{attributeId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - try { - // convert json to PropertyDefinition - Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); - // convert json to AttributeDefinition - - buildAttributeFromString(data, attributesWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); - // update property - if (eitherUpdateAttribute.isRight()) { - errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); - } else { - attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value()); - } - } - - Response response; - if (!errorWrapper.isEmpty()) { - log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); - } else { - PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); - log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); - log.debug("update attribute failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - /** - * Deletes existing Attribute with given attributeID on a resource with given resourceID - * - * @param resourceId - * @param attributeId - * @param request - * @param userId - * @return - */ - @DELETE - @Path("resources/{resourceId}/attributes/{attributeId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - log.debug("modifier id is {}", userId); - - try { - - // delete the property - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); - if (eitherAttribute.isRight()) { - log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); - return buildErrorResponse(eitherAttribute.right().value()); - } - PropertyDefinition attributeDefinition = eitherAttribute.left().value(); - String name = attributeDefinition.getName(); - - log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute"); - log.debug("delete attribute failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { - - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); - if (attribute == null) { - log.info("Attribute content is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - errorWrapper.setInnerElement(responseFormat); - } else { - attributesWrapper.setInnerElement(attribute); - } - - } catch (Exception e) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - errorWrapper.setInnerElement(responseFormat); - log.debug("Attribute content is invalid - {}", data, e); - log.info("Attribute content is invalid - {}", data); - } - } + private static final Logger log = LoggerFactory.getLogger(AttributeServlet.class); + + /** + * Creates new Attribute on a resource with given resource ID + * + * @param resourceId + * @param data + * @param request + * @param userId + * @return + */ + @POST + @Path("resources/{resourceId}/attributes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource attribute already exist") }) + public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + + try { + Wrapper errorWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); + // convert json to AttributeDefinition + + buildAttributeFromString(data, attributesWrapper, errorWrapper); + if (errorWrapper.isEmpty()) { + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); + if (createAttribute.isRight()) { + errorWrapper.setInnerElement(createAttribute.right().value()); + } else { + attributesWrapper.setInnerElement(createAttribute.left().value()); + } + } + + Response response; + if (!errorWrapper.isEmpty()) { + log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); + response = buildErrorResponse(errorWrapper.getInnerElement()); + } else { + PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); + log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); + log.debug("create property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + /** + * Updates existing Attribute with given attributeID on a resource with given resourceID + * + * @param resourceId + * @param attributeId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("resources/{resourceId}/attributes/{attributeId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + try { + // convert json to PropertyDefinition + Wrapper errorWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); + // convert json to AttributeDefinition + + buildAttributeFromString(data, attributesWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); + // update property + if (eitherUpdateAttribute.isRight()) { + errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); + } else { + attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value()); + } + } + + Response response; + if (!errorWrapper.isEmpty()) { + log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); + response = buildErrorResponse(errorWrapper.getInnerElement()); + } else { + PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); + log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); + log.debug("update attribute failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + /** + * Deletes existing Attribute with given attributeID on a resource with given resourceID + * + * @param resourceId + * @param attributeId + * @param request + * @param userId + * @return + */ + @DELETE + @Path("resources/{resourceId}/attributes/{attributeId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + log.debug("modifier id is {}", userId); + + try { + + // delete the property + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); + Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + if (eitherAttribute.isRight()) { + log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); + return buildErrorResponse(eitherAttribute.right().value()); + } + PropertyDefinition attributeDefinition = eitherAttribute.left().value(); + String name = attributeDefinition.getName(); + + log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute"); + log.debug("delete attribute failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { + + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); + if (attribute == null) { + log.info("Attribute content is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + errorWrapper.setInnerElement(responseFormat); + } else { + attributesWrapper.setInnerElement(attribute); + } + + } catch (Exception e) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + errorWrapper.setInnerElement(responseFormat); + log.debug("Attribute content is invalid - {}", data, e); + log.info("Attribute content is invalid - {}", data); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 7407a4dff3..0e0d20ffcb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,30 +20,24 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.Supplier; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - -import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import fj.data.Either; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; -import org.openecomp.sdc.be.components.impl.ProductComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.api.IElementDAO; @@ -51,204 +45,244 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.servlets.BasicServlet; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Supplier; public class BeGenericServlet extends BasicServlet { - @Context - protected HttpServletRequest servletRequest; - - private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName()); - - /******************** New error response mechanism - * @param additionalParams **************/ - - protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { - return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); - } - - protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { - return buildOkResponse(errorResponseWrapper, entity, null); - } - - protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map additionalHeaders) { - int status = errorResponseWrapper.getStatus(); - ResponseBuilder responseBuilder = Response.status(status); - if (entity != null) { - if (log.isTraceEnabled()) - log.trace("returned entity is {}", entity.toString()); - responseBuilder = responseBuilder.entity(entity); - } - if (additionalHeaders != null) { - for (Entry additionalHeader : additionalHeaders.entrySet()) { - String headerName = additionalHeader.getKey(); - String headerValue = additionalHeader.getValue(); - if (log.isTraceEnabled()) - log.trace("Adding header {} with value {} to the response", headerName, headerValue); - responseBuilder.header(headerName, headerValue); - } - } - return responseBuilder.build(); - } - - /*******************************************************************************************************/ - protected Either getUser(final HttpServletRequest request, String userId) { - Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); - if (eitherCreator.isRight()) { - log.info("createResource method - user is not listed. userId= {}", userId); - ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); - User user = new User("", "", userId, "", null, null); - - getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); - return Either.right(errorResponse); - } - return Either.left(eitherCreator.left().value()); - - } - - protected UserBusinessLogic getUserAdminManager(ServletContext context) { - return getClassFromWebAppContext(context, () -> UserBusinessLogic.class); - } - - protected ResourceBusinessLogic getResourceBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class); - } - - protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class); - } - - protected ServiceBusinessLogic getServiceBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class); - } - - protected ProductBusinessLogic getProductBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class); - } - - protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class); - } - - protected ElementBusinessLogic getElementBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class); - } - - protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class); - } - - protected AssetMetadataConverter getAssetUtils(ServletContext context) { - return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class); - } - - protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) { - return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class); - } - - protected SomeClass getClassFromWebAppContext(ServletContext context, Supplier> businessLogicClassGen) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get()); - return monitoringBusinessLogic; - } - - protected GroupBusinessLogic getGroupBL(ServletContext context) { - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - GroupBusinessLogic groupBusinessLogic = webApplicationContext.getBean(GroupBusinessLogic.class); - return groupBusinessLogic; - } - - protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - if (containerComponentType == ComponentTypeEnum.RESOURCE) { - return webApplicationContext.getBean(VFComponentInstanceBusinessLogic.class); - } - if (containerComponentType == ComponentTypeEnum.SERVICE) { - return webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class); - } - if (containerComponentType == ComponentTypeEnum.PRODUCT) { - return webApplicationContext.getBean(ProductComponentInstanceBusinessLogic.class); - } - return null; - } - - protected IElementDAO getElementDao(Class clazz, ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(clazz); - } - - protected ComponentsUtils getComponentsUtils() { - ServletContext context = this.servletRequest.getSession().getServletContext(); - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class); - return componentsUtils; - } - - /** - * Used to support Unit Test.
- * Header Params are not supported in Unit Tests - * - * @return - */ - protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) { - String retValue; - if (headerValue != null) { - retValue = headerValue; - } else { - retValue = request.getHeader(headerName); - } - return retValue; - } - - protected String getContentDispositionValue(String artifactFileName) { - return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString(); - } - - protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) { - ComponentBusinessLogic businessLogic; - switch (componentTypeEnum) { - case RESOURCE: { - businessLogic = getResourceBL(context); - break; - } - case SERVICE: { - businessLogic = getServiceBL(context); - break; - } - case PRODUCT: { - businessLogic = getProductBL(context); - break; - } - case RESOURCE_INSTANCE: { - businessLogic = getResourceBL(context); - break; - } - default: { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL"); - BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL"); - throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); - } - } - return businessLogic; - } + @Context + protected HttpServletRequest servletRequest; + + private static final Logger log = LoggerFactory.getLogger(BeGenericServlet.class); + + /******************** New error response mechanism + * @param requestErrorWrapper **************/ + + protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) { + return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build(); + } + + protected Response buildGeneralErrorResponse() { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + protected Response buildOkResponse(Object entity) { + return buildOkResponseStatic(entity); + } + + static public Response buildOkResponseStatic(Object entity) { + return Response.status(Response.Status.OK) + .entity(entity) + .build(); + } + + protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { + return buildOkResponse(errorResponseWrapper, entity, null); + } + + protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map additionalHeaders) { + int status = errorResponseWrapper.getStatus(); + ResponseBuilder responseBuilder = Response.status(status); + if (entity != null) { + if (log.isTraceEnabled()) + log.trace("returned entity is {}", entity.toString()); + responseBuilder = responseBuilder.entity(entity); + } + if (additionalHeaders != null) { + for (Entry additionalHeader : additionalHeaders.entrySet()) { + String headerName = additionalHeader.getKey(); + String headerValue = additionalHeader.getValue(); + if (log.isTraceEnabled()) + log.trace("Adding header {} with value {} to the response", headerName, headerValue); + responseBuilder.header(headerName, headerValue); + } + } + return responseBuilder.build(); + } + + /*******************************************************************************************************/ + protected Either getUser(final HttpServletRequest request, String userId) { + Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); + if (eitherCreator.isRight()) { + log.info("createResource method - user is not listed. userId= {}", userId); + ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); + User user = new User("", "", userId, "", null, null); + + getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(errorResponse); + } + return Either.left(eitherCreator.left().value()); + + } + + protected PolicyTypeBusinessLogic getPolicyTypeBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> PolicyTypeBusinessLogic.class); + } + + protected UserBusinessLogic getUserAdminManager(ServletContext context) { + return getClassFromWebAppContext(context, () -> UserBusinessLogic.class); + } + + protected ResourceBusinessLogic getResourceBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class); + } + + protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class); + } + + protected ServiceBusinessLogic getServiceBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class); + } + + protected ProductBusinessLogic getProductBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class); + } + + protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class); + } + + protected ElementBusinessLogic getElementBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class); + } + + protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class); + } + + protected AssetMetadataConverter getAssetUtils(ServletContext context) { + return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class); + } + + protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class); + } + + protected PolicyBusinessLogic getPolicyBL(ServletContext context) { + return getClassFromWebAppContext(context, () -> PolicyBusinessLogic.class); + } + + protected T getClassFromWebAppContext(ServletContext context, Supplier> businessLogicClassGen) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(businessLogicClassGen.get()); + } + + protected GroupBusinessLogic getGroupBL(ServletContext context) { + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(GroupBusinessLogic.class); + } + + protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentInstanceBusinessLogic.class); + } + + protected IElementDAO getElementDao(Class clazz, ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(clazz); + } + + protected ComponentsUtils getComponentsUtils() { + ServletContext context = this.servletRequest.getSession().getServletContext(); + + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(ComponentsUtils.class); + } + + /** + * Used to support Unit Test.
+ * Header Params are not supported in Unit Tests + * + * @return + */ + protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) { + String retValue; + if (headerValue != null) { + retValue = headerValue; + } else { + retValue = request.getHeader(headerName); + } + return retValue; + } + + protected String getContentDispositionValue(String artifactFileName) { + return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString(); + } + + protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) { + ComponentBusinessLogic businessLogic; + switch (componentTypeEnum) { + case RESOURCE: + businessLogic = getResourceBL(context); + break; + case SERVICE: + businessLogic = getServiceBL(context); + break; + case PRODUCT: + businessLogic = getProductBL(context); + break; + case RESOURCE_INSTANCE: + businessLogic = getResourceBL(context); + break; + default: + BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL"); + throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue()); + } + return businessLogic; + } + + protected void convertJsonToObjectOfClass(String json, Wrapper policyWrapper, Class clazz, Wrapper errorWrapper) { + T object = null; + ObjectMapper mapper = new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + try { + log.trace("Starting to convert json to object. Json=\n{}", json); + + SimpleModule module = new SimpleModule("customDeserializationModule"); + module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer()); + mapper.registerModule(module); + + object = mapper.readValue(json, clazz); + if (object != null) { + policyWrapper.setInnerElement(object); + } else { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("The object of class {} is null after converting from json. ", clazz); + errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("The exception {} occured upon json to object convertation. Json=\n{}", e, json); + errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java index 81f1775a01..aa10ce0dd4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java @@ -20,22 +20,16 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.lang3.tuple.Pair; -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,139 +44,135 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; @Loggable(prepend = true, value = Loggable.TRACE, trim = false) @Path("/") @Api(value = "BE Monitoring", description = "BE Monitoring") @Singleton public class BeMonitoringServlet extends BeGenericServlet { - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); - - @GET - @Path("/healthCheck") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") }) - public Response getHealthCheck(@Context final HttpServletRequest request) { - try { - HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext()); - Pair> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); - Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft(); - ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR; - String sdcVersion = getVersionFromContext(request); - if (sdcVersion == null || sdcVersion.isEmpty()) { - sdcVersion = "UNKNOWN"; - } - String siteMode = healthCheckBusinessLogic.getSiteMode(); - HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode); - // The response can be either with 200 or 500 aggregate status - the - // body of individual statuses is returned either way - - String healthCheckStr = prettyGson.toJson(healthCheck); - return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, "BeHealthCheck"); - BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck"); - log.debug("BE health check unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/monitoring") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) { - try { - MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class); - if (monitoringEvent == null) { - return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); - } - log.trace("Received monitoring metrics: {}", monitoringEvent.toString()); - ServletContext context = request.getSession().getServletContext(); - MonitoringBusinessLogic bl = getMonitoringBL(context); - Either result = bl.logMonitoringEvent(monitoringEvent); - if (result.isRight()) { - return buildErrorResponse(result.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - - } catch (Exception e) { - log.debug("BE system metrics unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/version") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") }) - public Response getSdcVersion(@Context final HttpServletRequest request) { - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - String version = getVersionFromContext(request); - log.debug("asdc version from manifest is: {}", version); - if (version == null || version.isEmpty()) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND)); - } - - HealthCheckInfo versionInfo = new HealthCheckInfo(); - versionInfo.setVersion(version); - - // The response can be either with 200 or 500 aggregate status - the - // body of individual statuses is returned either way - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); - log.debug("BE get ASDC version unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private String getVersionFromContext(HttpServletRequest request) { - ServletContext servletContext = request.getSession().getServletContext(); - String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); - return version; - } - - protected MonitoringEvent convertContentToJson(String content, Class clazz) { - - MonitoringEvent object = null; - try { - object = gson.fromJson(content, clazz); - object.setFields(null); - } catch (Exception e) { - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return object; - } - - private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); - return healthCheckBl; - } + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class); + + @GET + @Path("/healthCheck") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") }) + public Response getHealthCheck(@Context final HttpServletRequest request) { + try { + HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext()); + Pair> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus(); + Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft(); + ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR; + String sdcVersion = getVersionFromContext(request); + if (sdcVersion == null || sdcVersion.isEmpty()) { + sdcVersion = "UNKNOWN"; + } + String siteMode = healthCheckBusinessLogic.getSiteMode(); + HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode); + // The response can be either with 200 or 500 aggregate status - the + // body of individual statuses is returned either way + + String healthCheckStr = prettyGson.toJson(healthCheck); + return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck"); + log.debug("BE health check unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/monitoring") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) { + try { + MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class); + if (monitoringEvent == null) { + return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); + } + log.trace("Received monitoring metrics: {}", monitoringEvent); + ServletContext context = request.getSession().getServletContext(); + MonitoringBusinessLogic bl = getMonitoringBL(context); + Either result = bl.logMonitoringEvent(monitoringEvent); + if (result.isRight()) { + return buildErrorResponse(result.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + + } catch (Exception e) { + log.debug("BE system metrics unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/version") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") }) + public Response getSdcVersion(@Context final HttpServletRequest request) { + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + String version = getVersionFromContext(request); + log.debug("asdc version from manifest is: {}", version); + if (version == null || version.isEmpty()) { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND)); + } + + HealthCheckInfo versionInfo = new HealthCheckInfo(); + versionInfo.setVersion(version); + + // The response can be either with 200 or 500 aggregate status - the + // body of individual statuses is returned either way + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion"); + log.debug("BE get ASDC version unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private String getVersionFromContext(HttpServletRequest request) { + ServletContext servletContext = request.getSession().getServletContext(); + String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR); + return version; + } + + protected MonitoringEvent convertContentToJson(String content, Class clazz) { + + MonitoringEvent object = null; + try { + object = gson.fromJson(content, clazz); + object.setFields(null); + } catch (Exception e) { + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return object; + } + + private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class); + return healthCheckBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java new file mode 100644 index 0000000000..8ed68fa032 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.servlets; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class ComponentExceptionMapper implements ExceptionMapper { + + private final ComponentsUtils componentsUtils; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public ComponentExceptionMapper(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @Override + public Response toResponse(ComponentException componentException) { + ResponseFormat responseFormat = componentException.getResponseFormat(); + if (componentException.getResponseFormat()==null) { + responseFormat = componentsUtils.getResponseFormat(componentException.getActionStatus(), componentException.getParams()); + } + + return Response.status(responseFormat.getStatus()) + .entity(gson.toJson(responseFormat.getRequestError())) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index b5971670cf..536fdc3c7e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -20,36 +20,26 @@ package org.openecomp.sdc.be.servlets; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; -import org.codehaus.jackson.map.ObjectMapper; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.ForwardingPaths; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.ComponentInstance; @@ -60,24 +50,34 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; /** * Root resource (exposed at "/" path) .json @@ -88,853 +88,390 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ComponentInstanceServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class.getName()); - - Type constraintType = new TypeToken() { - }.getType(); - - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Component instance already exist") }) - public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - try { - - ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); - componentInstance.setInvariantName(null); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); - log.debug("create component instance failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - log.debug("Start handle request of {}", url); - - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either convertResponse = convertToResourceInstance(data); - - if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - ComponentInstance resourceInstance = convertResponse.left().value(); - Either actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - log.debug("Start handle request of {}", url); - - if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) { - log.info("Empty JSON list was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray); - - if (convertResponse.isRight()) { - // Using both ECOMP error methods, show to Sofer - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - List componentInstanceList = convertResponse.left().value(); - - Either, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - /* - * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeRestApiGeneralError, "Update Resource Instance" ); - */ - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - Response response = null; - try { - log.debug("Start handle request of {}", url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - String userId = request.getHeader(Constants.USER_ID_HEADER); - Either actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); - log.debug("delete resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/associate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Relationship already exist") }) - public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - - try { - - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either regInfoW = convertToRequirementCapabilityRelDef(data); - - Either resultOp; - if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI"); - log.debug("Failed to convert received data to BE format."); - resultOp = Either.right(regInfoW.right().value()); - } else { - RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); - resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); - } - - Either actionResponse = resultOp; - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); - log.debug("associate resource instance to another RI with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @PUT - @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response dissociateRIFromRI( - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either regInfoW = convertToRequirementCapabilityRelDef(data); - if (regInfoW.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(regInfoW.right().value()); - } - - RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); - Either actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); - log.debug("dissociate resource instance from service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Relationship already exist") }) - public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - log.debug("Start handle request of {}", url); - - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class); - if (convertStatus.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI"); - log.debug("Failed to convert received data to BE format."); - Either formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); - return buildErrorResponse(formattedResponse.right().value()); - } - - CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value(); - Either actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance"); - log.debug("create and associate RI failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper dataWrapper = new Wrapper<>(); - Wrapper errorWrapper = new Wrapper<>(); - Wrapper propertyWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (!errorWrapper.isEmpty()) { - return buildErrorResponse(errorWrapper.getInnerElement()); - } - - ComponentInstanceProperty property = propertyWrapper.getInnerElement(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either actionResponse = componentInstanceLogic.createOrUpdatePropertyValue(componentTypeEnum, componentId, componentInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper dataWrapper = new Wrapper<>(); - Wrapper errorWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - ComponentInstanceInput property = null; - - if (errorWrapper.isEmpty()) { - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, - ComponentTypeEnum.SERVICE); - ; - if (inputEither.isRight()) { - log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - property = inputEither.left().value(); - - } - - if (property == null) { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - /** - * Updates ResourceInstance Attribute - * - * @param componentId - * @param containerComponentType - * @param componentInstanceId - * @param userId - * @param request - * @return - */ - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - - Wrapper errorWrapper = new Wrapper<>(); - Wrapper dataWrapper = new Wrapper<>(); - Wrapper attributeWrapper = new Wrapper<>(); - Wrapper blWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); - Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); - if (eitherAttribute.isRight()) { - errorWrapper.setInnerElement(eitherAttribute.right().value()); - } else { - attributeWrapper.setInnerElement(eitherAttribute.left().value()); - } - } - - return buildResponseFromElement(errorWrapper, attributeWrapper); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @DELETE - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); - - if (bytes == null || bytes.length == 0) { - log.info("Empty body was sent."); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either convertResponse = convertToResourceInstance(data); - - if (convertResponse.isRight()) { - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); - log.debug("Failed to convert received data to BE format."); - return buildErrorResponse(convertResponse.right().value()); - } - - ComponentInstance newResourceInstance = convertResponse.left().value(); - Either actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); - log.debug("update resource instance with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @POST - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - try { - Wrapper dataWrapper = new Wrapper<>(); - Wrapper errorWrapper = new Wrapper<>(); - Wrapper propertyWrapper = new Wrapper<>(); - - validateInputStream(request, dataWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); - } - - if (!errorWrapper.isEmpty()) { - return buildErrorResponse(errorWrapper.getInnerElement()); - } - - ComponentInstanceProperty property = propertyWrapper.getInnerElement(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); - - ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @GET - @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) - public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, - @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - - GroupBusinessLogic businessLogic = this.getGroupBL(context); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", containerComponentType); - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - // US831698 - @GET - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") }) - public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); - - Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); - - if (componentInstancePropertiesById.isRight()) { - log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); - return buildErrorResponse(componentInstancePropertiesById.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - // US330353 - @GET - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) - public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); - - Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, - capabilityType, capabilityName, userId); - - if (componentInstancePropertiesById.isRight()) { - log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); - return buildErrorResponse(componentInstancePropertiesById.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } + private static final Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class); - private Either, ResponseFormat> convertMultipleProperties(String dataList) { - if (StringUtils.isEmpty(dataList)) { - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + Type constraintType = new TypeToken() { + }.getType(); + + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Component instance already exist") }) + public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + try { + + ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); + componentInstance.setInvariantName(null); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance"); + log.debug("create component instance failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + log.debug("Start handle request of {}", url); + + InputStream inputStream = request.getInputStream(); + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either convertResponse = convertToResourceInstance(data); + + if (convertResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + ComponentInstance resourceInstance = convertResponse.left().value(); + Either actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + log.debug("Start handle request of {}", url); + + if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) { + log.info("Empty JSON list was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray); + + if (convertResponse.isRight()) { + // Using both ECOMP error methods, show to Sofer + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + List componentInstanceList = convertResponse.left().value(); + + Either, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + Response response = null; + try { + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + String userId = request.getHeader(Constants.USER_ID_HEADER); + Either actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); + log.debug("delete resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/associate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Relationship already exist") }) + public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + + try { + + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either regInfoW = convertToRequirementCapabilityRelDef(data); + + Either resultOp; + if (regInfoW.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI"); + log.debug("Failed to convert received data to BE format."); + resultOp = Either.right(regInfoW.right().value()); + } else { + RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); + resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum); + } + + Either actionResponse = resultOp; + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance"); + log.debug("associate resource instance to another RI with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } - return Either.left(Arrays.asList(convertStatus.left().value())); } - //US 331281 @PUT - @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties") + @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Instance Capabilty Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) - public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, - @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, - @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response dissociateRIFromRI( + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) { ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(PUT) Start handle request of {}", url); + log.debug("Start handle request of {}", url); + + try { + + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either regInfoW = convertToRequirementCapabilityRelDef(data); + if (regInfoW.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(regInfoW.right().value()); + } + + RequirementCapabilityRelDef requirementDef = regInfoW.left().value(); + Either actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance"); + log.debug("dissociate resource instance from service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Relationship already exist") }) + public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + log.debug("Start handle request of {}", url); + + InputStream inputStream = request.getInputStream(); + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class); + if (convertStatus.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI"); + log.debug("Failed to convert received data to BE format."); + Either formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); + return buildErrorResponse(formattedResponse.right().value()); + } + + CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value(); + Either actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance"); + log.debug("create and associate RI failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceProperties(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { Wrapper errorWrapper = new Wrapper<>(); List propertiesToUpdate = new ArrayList<>(); if (errorWrapper.isEmpty()) { - Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(data); + Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray); if (propertiesToUpdateEither.isRight()) { errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); } else { @@ -946,226 +483,736 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildErrorResponse(errorWrapper.getInnerElement()); } + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", propertiesToUpdate); + + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } - Either, ResponseFormat> updateCICapProperty = componentInstanceBL.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId); + Either, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId); - if (updateCICapProperty.isRight()) { - log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); - return buildErrorResponse(updateCICapProperty.right().value()); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value()); + List resourceInstanceProperties = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperties); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper errorWrapper = new Wrapper<>(); + List inputsToUpdate = new ArrayList<>(); + if (errorWrapper.isEmpty()) { + Either, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray); + if (inputsToUpdateEither.isRight()) { + errorWrapper.setInnerElement(inputsToUpdateEither.right().value()); + } else { + inputsToUpdate = inputsToUpdateEither.left().value(); + } + } + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", inputsToUpdate); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either, ResponseFormat> actionResponse = + componentInstanceLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + List resourceInstanceInput = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceInput); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + /** + * Updates ResourceInstance Attribute + * + * @param componentId + * @param containerComponentType + * @param componentInstanceId + * @param userId + * @param request + * @return + */ + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + + Wrapper errorWrapper = new Wrapper<>(); + Wrapper dataWrapper = new Wrapper<>(); + Wrapper attributeWrapper = new Wrapper<>(); + Wrapper blWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); + Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); + if (eitherAttribute.isRight()) { + errorWrapper.setInnerElement(eitherAttribute.right().value()); + } else { + attributeWrapper.setInnerElement(eitherAttribute.left().value()); + } + } + + return buildResponseFromElement(errorWrapper, attributeWrapper); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try ( InputStream inputStream = request.getInputStream()) { + + byte[] bytes = IOUtils.toByteArray(inputStream); + + if (bytes == null || bytes.length == 0) { + log.info("Empty body was sent."); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + String data = new String(bytes); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either convertResponse = convertToResourceInstance(data); + + if (convertResponse.isRight()) { + BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance"); + log.debug("Failed to convert received data to BE format."); + return buildErrorResponse(convertResponse.right().value()); + } + + ComponentInstance newResourceInstance = convertResponse.left().value(); + Either actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance"); + log.debug("update resource instance with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @POST + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + try { + Wrapper dataWrapper = new Wrapper<>(); + Wrapper errorWrapper = new Wrapper<>(); + Wrapper propertyWrapper = new Wrapper<>(); + + validateInputStream(request, dataWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper); + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + ComponentInstanceProperty property = propertyWrapper.getInnerElement(); + + log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property); + + ServletContext context = request.getSession().getServletContext(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + + Either actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(resourceInstanceProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @GET + @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") }) + public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, + @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", containerComponentType); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + // US831698 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") }) + public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); + + if (componentInstancePropertiesById.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(componentInstancePropertiesById.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + // US330353 + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) + public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, + capabilityType, capabilityName, ownerId, userId); + + if (componentInstancePropertiesById.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(componentInstancePropertiesById.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + //US 331281 + @PUT + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Instance Capabilty Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") }) + public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId, + @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(PUT) Start handle request of {}", url); + try { + Wrapper errorWrapper = new Wrapper<>(); + List propertiesToUpdate = new ArrayList<>(); + if (errorWrapper.isEmpty()) { + Either, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(data); + if (propertiesToUpdateEither.isRight()) { + errorWrapper.setInnerElement(propertiesToUpdateEither.right().value()); + } else { + propertiesToUpdate = propertiesToUpdateEither.left().value(); + } + } + + if (!errorWrapper.isEmpty()) { + return buildErrorResponse(errorWrapper.getInnerElement()); + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum); + + Either, ResponseFormat> updateCICapProperty = componentInstanceBL.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId); + + if (updateCICapProperty.isRight()) { + log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId); + return buildErrorResponse(updateCICapProperty.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Service proxy already exist") }) + public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + try { + + ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); + componentInstance.setInvariantName(null); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + if (componentTypeEnum != ComponentTypeEnum.SERVICE) { + log.debug("Unsupported container component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy"); + log.debug("Create service proxy failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, + @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + Response response = null; + try { + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + String userId = request.getHeader(Constants.USER_ID_HEADER); + Either actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + } + return response; + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy"); + log.debug("Delete service proxy failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @POST + @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + try { + + String userId = request.getHeader(Constants.USER_ID_HEADER); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + Either actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version"); + log.debug("Update service proxy with new version failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + /** + * REST API GET relation by Id + * Allows to get relation contained in specified component according to received Id + * @param containerComponentType + * @param componentId + * @param relationId + * @param request + * @param userId + * @return Response + */ + @GET + @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") }) + public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, + @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + if (componentTypeEnum == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + + Either actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById"); + log.debug("getRelationById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private Either convertToResourceInstance(String data) { + + // Either convertStatus = + // convertJsonToObject(data, ComponentInstance.class); + Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + ComponentInstance resourceInstanceInfo = convertStatus.left().value(); + + return Either.left(resourceInstanceInfo); + } + + private Either, ResponseFormat> convertToMultipleResourceInstance(String dataList) { + + Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + private Either, ResponseFormat> convertMultipleProperties(String dataList) { + if (StringUtils.isEmpty(dataList)) { + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + private Either, ResponseFormat> convertMultipleInputs(String dataList) { + if (StringUtils.isEmpty(dataList)) { + return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); + if (convertStatus.isRight()) { + return Either.right(convertStatus.right().value()); + } + return Either.left(Arrays.asList(convertStatus.left().value())); + } + + + private Either convertToRequirementCapabilityRelDef(String data) { + + Either convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class); + if (convertStatus.isRight()) { + return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); + } + RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value(); + return Either.left(requirementCapabilityRelDef); + } + + private Either convertJsonToObject(String data, Class clazz) { + try { + log.trace("convert json to object. json=\n {}", data); + T t; + t = gson.fromJson(data, clazz); + if (t == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(t); + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } + + + @GET + @Path("/{containerComponentType}/{componentId}/paths-to-delete") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Check if forwarding path to delete on version change", httpMethod = "GET", notes = "Returns forwarding paths to delete", + response = Response.class) + public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId, + @QueryParam("componentInstanceId") final String oldComponentInstanceId, + @QueryParam("newComponentInstanceId") final String newComponentInstanceId, + @ApiParam(value = "valid values: resources / services", + allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) + @PathParam("containerComponentType") final String containerComponentType, + @Context final HttpServletRequest request) { + if (oldComponentInstanceId == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE)); + } + if (newComponentInstanceId == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE)); + } + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); + if (componentInstanceLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + } + ComponentInstance newComponentInstance; + if(StringUtils.isNotEmpty(newComponentInstanceId)){ + newComponentInstance=new ComponentInstance(); + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId); + }else{ + log.error("missing component id"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA)); + } + Either,ResponseFormat> actionResponse= componentInstanceLogic.forwardingPathOnVersionChange( + containerComponentType,componentId,oldComponentInstanceId,newComponentInstance); + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + ForwardingPaths forwardingPaths=new ForwardingPaths(); + forwardingPaths.setForwardingPathToDelete(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths); + } - @POST - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Service proxy already exist") }) - public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - try { - - ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class); - componentInstance.setInvariantName(null); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.debug("Unsupported container component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy"); - log.debug("Create service proxy failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @DELETE - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, - @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - Response response = null; - try { - log.debug("Start handle request of {}", url); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - String userId = request.getHeader(Constants.USER_ID_HEADER); - Either actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - } - return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy"); - log.debug("Delete service proxy failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @POST - @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId, - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - try { - - String userId = request.getHeader(Constants.USER_ID_HEADER); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - Either actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version"); - log.debug("Update service proxy with new version failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - /** - * REST API GET relation by Id - * Allows to get relation contained in specified component according to received Id - * @param containerComponentType - * @param componentId - * @param relationId - * @param request - * @param userId - * @return Response - */ - @GET - @Path("/{containerComponentType}/{componentId}/relationId/{relationId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") }) - public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, - @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum); - if (componentInstanceLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); - } - - Either actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum); - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById"); - log.debug("getRelationById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private Either convertToResourceInstance(String data) { - - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); - } - ComponentInstance resourceInstanceInfo = convertStatus.left().value(); - - return Either.left(resourceInstanceInfo); - } - - private Either, ResponseFormat> convertToMultipleResourceInstance(String dataList) { - - Either convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE); - if (convertStatus.isRight()) { - return Either.right(convertStatus.right().value()); - } - - return Either.left(Arrays.asList(convertStatus.left().value())); - } - - private Either convertToRequirementCapabilityRelDef(String data) { - - Either convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class); - if (convertStatus.isRight()) { - return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value())); - } - RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value(); - return Either.left(requirementCapabilityRelDef); - } - - private Either convertJsonToObject(String data, Class clazz) { - try { - log.trace("convert json to object. json=\n {}", data); - T t = null; - t = gson.fromJson(data, clazz); - if (t == null) { - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(t); - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java index 0c955f4e5a..16fa67e7cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java @@ -20,26 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -59,345 +46,354 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Component Servlet", description = "Component Servlet") @Singleton public class ComponentServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName()); - - @GET - @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - Response response; - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum != null) { - ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); - if (eitherConformanceLevel.isRight()) { - response = buildErrorResponse(eitherConformanceLevel.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); - } - } else { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return response; - } - - @GET - @Path("/{componentType}/{componentId}/requirmentsCapabilities") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - Response response; - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - if (componentTypeEnum != null) { - try { - ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); - if (eitherRequirementsAndCapabilities.isRight()) { - response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); - } else { - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value())); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); - log.debug("getRequirementAndCapabilities failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } else { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - return response; - } - - @GET - @Path("/{componentType}/latestversion/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @QueryParam("componentUids") List componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @POST - @Path("/{componentType}/latestversion/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List data) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - - try { - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - List componentUids = data; - if (log.isDebugEnabled()) - log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size())); - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); - - if (actionResponse.isRight()) { - if (log.isDebugEnabled()) - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - return responseToReturn; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @GET - @Path("/{componentType}/latestversion/notabstract/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); - log.debug("getCertifiedNotAbstractComponents failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @GET - @Path("/{componentType}/{componentId}/componentInstances") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - Either, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText); - if (actionResponse.isRight()) { - log.debug("failed to get all component instances filtered by properties and inputs", componentType); - return buildErrorResponse(actionResponse.right().value()); - } - Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType); - log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - - - /** - * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. - * for example: list of the string "properties, inputs" will return component with the list of properties and inputs. - * - * @param componentType - * @param componentId - * @param dataParamsToReturn - * @param request - * @param userId - * @return - */ - - @GET - @Path("/{componentType}/{componentId}/filteredDataByParams") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = componentId.toLowerCase(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - - log.trace("get component with id {} filtered by ui params", componentId); - Either actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); - - if (actionResponse.isRight()) { - log.debug("failed to get component data filtered by ui params"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - - @GET - @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getFilteredComponentInstanceProperties( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("propertyNameFragment") final String propertyNameFragment, - @QueryParam("resourceType") List resourceTypes, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - User user = new User(); - user.setUserId(userId); - log.debug("User Id is {}" , userId); - Response response = null; - try { - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); - Map> filters = new EnumMap<>(FilterKeyEnum.class); - List propertyNameFragments = new ArrayList<>(); - propertyNameFragments.add(propertyNameFragment); - filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); - if(CollectionUtils.isNotEmpty(resourceTypes)){ - filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); - } - Either>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties"); - log.debug("Getting of filtered component instance properties failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } + private static final Logger log = LoggerFactory.getLogger(ComponentServlet.class); + + @GET + @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + Response response; + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum != null) { + ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); + Either eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); + if (eitherConformanceLevel.isRight()) { + response = buildErrorResponse(eitherConformanceLevel.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value())); + } + } else { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return response; + } + + @GET + @Path("/{componentType}/{componentId}/requirmentsCapabilities") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + Response response; + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + if (componentTypeEnum != null) { + try { + ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); + Either eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId); + if (eitherRequirementsAndCapabilities.isRight()) { + response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value()); + } else { + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value())); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId); + log.debug("getRequirementAndCapabilities failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } else { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + return response; + } + + @GET + @Path("/{componentType}/latestversion/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @QueryParam("componentUids") List componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); + + Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @POST + @Path("/{componentType}/latestversion/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List data) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + + try { + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + List componentUids = data; + if (log.isDebugEnabled()) + log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size()); + + Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId); + + if (actionResponse.isRight()) { + if (log.isDebugEnabled()) + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + return responseToReturn; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @GET + @Path("/{componentType}/latestversion/notabstract/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId); + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType); + log.debug("getCertifiedNotAbstractComponents failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @GET + @Path("/{componentType}/{componentId}/componentInstances") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + Either, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText); + if (actionResponse.isRight()) { + log.debug("failed to get all component instances filtered by properties and inputs", componentType); + return buildErrorResponse(actionResponse.right().value()); + } + Object components = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType); + log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + + /** + * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. + * for example: list of the string "properties, inputs" will return component with the list of properties and inputs. + * + * @param componentType + * @param componentId + * @param dataParamsToReturn + * @param request + * @param userId + * @return + */ + + @GET + @Path("/{componentType}/{componentId}/filteredDataByParams") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response; + + try { + String resourceIdLower = componentId.toLowerCase(); + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + + log.trace("get component with id {} filtered by ui params", componentId); + Either actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn); + + if (actionResponse.isRight()) { + log.debug("failed to get component data filtered by ui params"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + + @GET + @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getFilteredComponentInstanceProperties( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("propertyNameFragment") final String propertyNameFragment, + @QueryParam("resourceType") List resourceTypes, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + User user = new User(); + user.setUserId(userId); + log.debug("User Id is {}" , userId); + Response response; + try { + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context); + Map> filters = new EnumMap<>(FilterKeyEnum.class); + List propertyNameFragments = new ArrayList<>(); + propertyNameFragments.add(propertyNameFragment); + filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments); + if(CollectionUtils.isNotEmpty(resourceTypes)){ + filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes); + } + Either>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId); + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties"); + log.debug("Getting of filtered component instance properties failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java index 164b1d7665..f8aa39c478 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java @@ -20,18 +20,7 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - +import com.jcabi.aspects.Loggable; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.common.api.Constants; @@ -39,7 +28,11 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "/" path) @@ -48,78 +41,78 @@ import com.jcabi.aspects.Loggable; @Path("/configmgr") public class ConfigMgrServlet extends BasicServlet { - private static Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class); - @GET - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) { - String result = null; + String result = null; - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); + ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR); - if (type == null || type.equals("configuration")) { + if (type == null || type.equals("configuration")) { - Configuration configuration = configurationManager.getConfiguration(); - if (configuration == null) { - log.warn("Configuration of type {} was not found", Configuration.class); - } else { - log.info("The value returned from getConfig is {}", configuration); + Configuration configuration = configurationManager.getConfiguration(); + if (configuration == null) { + log.warn("Configuration of type {} was not found", Configuration.class); + } else { + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } - } + } + } - return result; + return result; - } + } - @POST - @Path("/set1") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) { + @POST + @Path("/set1") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - return "ok"; + return "ok"; - } + } - @POST - @Path("/set2") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) { + @POST + @Path("/set2") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - } + } - @PUT - @Path("/setput1") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) { + @PUT + @Path("/setput1") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - return "ok"; + return "ok"; - } + } - @PUT - @Path("/setput2") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.APPLICATION_JSON) - public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) { + @PUT + @Path("/setput2") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.APPLICATION_JSON) + public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) { - log.debug("{}", configuration); + log.debug("{}", configuration); - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java index 79202ac94f..a56065fcdf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - +import com.jcabi.aspects.Loggable; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.api.Constants; @@ -35,7 +28,13 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "/" path) @@ -44,36 +43,36 @@ import com.jcabi.aspects.Loggable; @Path("/config") public class ConfigServlet extends BasicServlet { - private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class); - @GET - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public String getConfig(@Context final HttpServletRequest request) { + @GET + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public String getConfig(@Context final HttpServletRequest request) { - String result = null; + String result = null; - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR); - if (configurationSource != null) { - Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null); + ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR); + if (configurationSource != null) { + Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null); - if (configuration == null) { - log.warn("Configuration of type {} was not found", Configuration.class); - } - log.debug("{}", configuration); - log.info("Info level ENABLED..."); - log.info("The value returned from getConfig is {}", configuration); + if (configuration == null) { + log.warn("Configuration of type {} was not found", Configuration.class); + } + log.debug("{}", configuration); + log.info("Info level ENABLED..."); + log.info("The value returned from getConfig is {}", configuration); - result = gson.toJson(configuration); + result = gson.toJson(configuration); - } else { - log.warn("Source Configuration object was not initialized in the context."); - } + } else { + log.warn("Source Configuration object was not initialized in the context."); + } - return result; + return result; - } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java index 943ed59e87..fda31e5032 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java @@ -20,21 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,179 +38,173 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/consumers") @Api(value = "Consumer Servlet", description = "Consumer Servlet") @Singleton public class ConsumerServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ConsumerServlet.class.getName()); + private static final Logger log = LoggerFactory.getLogger(ConsumerServlet.class); - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ONAP consumer credentials", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ECOMP consumer credentials", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); + ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); - Either convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); + Either convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS); - if (convertionResponse.isRight()) { - log.debug("failed to create Consumer"); - return buildErrorResponse(convertionResponse.right().value()); - } + if (convertionResponse.isRight()) { + log.debug("failed to create Consumer"); + return buildErrorResponse(convertionResponse.right().value()); + } - ConsumerDefinition consumer = convertionResponse.left().value(); + ConsumerDefinition consumer = convertionResponse.left().value(); - Either actionResult = businessLogic.createConsumer(modifier, consumer); + Either actionResult = businessLogic.createConsumer(modifier, consumer); - if (actionResult.isRight()) { - log.debug("failed to create Consumer"); - return buildErrorResponse(actionResult.right().value()); - } + if (actionResult.isRight()) { + log.debug("failed to create Consumer"); + return buildErrorResponse(actionResult.right().value()); + } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer"); - log.debug("create consumer failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @GET - @Path("/{consumerId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) - public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); - - Either actionResponse = businessLogic.getConsumer(consumerId, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get consumer"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); - log.debug("get consumer failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/{consumerId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) - public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ConsumerBusinessLogic businessLogic = getConsumerBL(context); - - Either actionResponse = businessLogic.deleteConsumer(consumerId, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to delete consumer"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); - log.debug("delete consumer failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - private ConsumerBusinessLogic getConsumerBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class); - - return consumerBL; - } - - public Either convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) { - ConsumerDefinition consumer = null; - Gson gson = new Gson(); - try { - log.trace("convert json to object. json=\n {}", data); - consumer = gson.fromJson(data, ConsumerDefinition.class); - if (consumer == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("object is null after converting from json"); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - } catch (Exception e) { - // INVALID JSON - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", data, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum); - return Either.right(responseFormat); - } - return Either.left(consumer); - } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer"); + log.debug("create consumer failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @GET + @Path("/{consumerId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) + public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); + + Either actionResponse = businessLogic.getConsumer(consumerId, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get consumer"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); + log.debug("get consumer failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/{consumerId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") }) + public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ConsumerBusinessLogic businessLogic = getConsumerBL(context); + + Either actionResponse = businessLogic.deleteConsumer(consumerId, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to delete consumer"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer"); + log.debug("delete consumer failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + private ConsumerBusinessLogic getConsumerBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class); + + return consumerBL; + } + + public Either convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) { + ConsumerDefinition consumer = null; + Gson gson = new Gson(); + try { + log.trace("convert json to object. json=\n {}", data); + consumer = gson.fromJson(data, ConsumerDefinition.class); + if (consumer == null) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("object is null after converting from json"); + //TODO call correct audit event method!!! - consumer!!! + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum); + return Either.right(responseFormat); + } + } catch (Exception e) { + // INVALID JSON + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", data, e); + //TODO call correct audit event method!!! - consumer!!! + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum); + return Either.right(responseFormat); + } + return Either.left(consumer); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java index 4f8bffa066..faf02dc5ca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java @@ -20,12 +20,10 @@ package org.openecomp.sdc.be.servlets; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; - +import com.jcabi.aspects.Loggable; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -33,122 +31,78 @@ import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; -import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jcabi.aspects.Loggable; -//import org.openecomp.sdc.be.builders.tosca.api.TopologyService; -//import org.openecomp.sdc.be.tosca.parsers.ParserMode; - @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/services") public class CsarBuildServlet extends ToscaDaoServlet { - private static Logger log = LoggerFactory.getLogger(CsarBuildServlet.class.getName()); - - @GET - @Path("/{serviceName}/{serviceVersion}") - public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { - - return null;// buildToscaCsar(request, serviceName, serviceVersion); - - } - - @GET - @Path("/{serviceName}/{serviceVersion}/csar") - public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { - - return null; // buildToscaCsar(request, serviceName, serviceVersion); - - } - - /* - * private Response buildToscaCsar(final HttpServletRequest request, String serviceName, String serviceVersion) { log.debug("Building CSAR for service:{} , version:{}", serviceName, serviceVersion); ServletContext context = - * request.getSession().getServletContext(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); String fileName = - * serviceName+"_"+serviceVersion+".zip"; - * - * IResourceUploader resourceUploader = getResourceUploader(context); TopologyService topologyService = getToscaYamlBuilder(context).getServiceYaml(serviceName, serviceVersion, ParserMode.CSAR, "Scripts"); try { - * - * - * //Add Service yml to Zip addZipEntry(zipOutputStream, "Definitions/"+serviceName+".yaml", topologyService.getTopologyServiceYaml()); - * - * //Add Resources to Zip addResourcesToZip(zipOutputStream, topologyService); - * - * //Add Artifacts to Zip addArtifactsToZip(serviceName, serviceVersion, zipOutputStream, resourceUploader); - * - * //Prepare Tosca metadata addToscaMetaToZip(zipOutputStream, topologyService, resourceUploader); - * - * } - * - * catch (IOException e) { log.error("Failed to create CSAR file", e); return null; } finally{ try { byteArrayOutputStream.close(); zipOutputStream.close(); } catch (IOException e) { log.error("Failed to close output srream", e); } - * - * } return buildResponse(fileName, byteArrayOutputStream); - * - * - * } - */ - - public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; - - protected String[] prepareToscaMetaHeader(String serviceName) { - return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n", - "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" }; - } - - protected String getAppliactionMime(String fileName) { - String mimeType; - if (fileName.contains(".sh")) { - mimeType = "x-sh"; - } else if (fileName.contains(".yang")) { - mimeType = "yang"; - } - - else if (fileName.contains(".rar")) { - mimeType = "x-rar-compressed"; - } - - else if (fileName.contains(".zip")) { - mimeType = "zip"; - } - - else if (fileName.contains(".tar")) { - mimeType = "x-tar"; - } - - else if (fileName.contains(".7z")) { - mimeType = "x-7z-compressed"; - } - - else { - // Undefined - mimeType = "undefined"; - } - return mimeType; - } - - protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) { - // return "Scripts/"+nodeTamplateName+"/"+ - // artifactData.getArtifactName(); - return "Scripts/" + nodeTamplateName + "/" + artifactData.getId(); - } - - protected String getResourcePath(String resourceName) { - return "Definitions/" + resourceName + ".yaml"; - } - - private byte[] encodeString(String data) throws CharacterCodingException { - Charset charset = Charset.forName("UTF-8"); - CharsetEncoder encoder = charset.newEncoder(); - ByteBuffer bb = encoder.encode(CharBuffer.wrap(data.toCharArray())); - byte[] ba = new byte[bb.limit()]; - bb.get(ba); - return ba; - } - - @Override - public Logger getLogger() { - return log; - } + private static final Logger log = LoggerFactory.getLogger(CsarBuildServlet.class); + + @GET + @Path("/{serviceName}/{serviceVersion}") + public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { + + return null;// buildToscaCsar(request, serviceName, serviceVersion); + + } + + @GET + @Path("/{serviceName}/{serviceVersion}/csar") + public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) { + + return null; // buildToscaCsar(request, serviceName, serviceVersion); + + } + + + public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; + + protected String[] prepareToscaMetaHeader(String serviceName) { + return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n", + "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" }; + } + + protected String getAppliactionMime(String fileName) { + String mimeType; + if (fileName.contains(".sh")) { + mimeType = "x-sh"; + } else if (fileName.contains(".yang")) { + mimeType = "yang"; + } + + else if (fileName.contains(".rar")) { + mimeType = "x-rar-compressed"; + } + + else if (fileName.contains(".zip")) { + mimeType = "zip"; + } + + else if (fileName.contains(".tar")) { + mimeType = "x-tar"; + } + + else if (fileName.contains(".7z")) { + mimeType = "x-7z-compressed"; + } + + else { + // Undefined + mimeType = "undefined"; + } + return mimeType; + } + + protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) { + return "Scripts/" + nodeTamplateName + "/" + artifactData.getId(); + } + + protected String getResourcePath(String resourceName) { + return "Definitions/" + resourceName + ".yaml"; + } + + @Override + public Logger getLogger() { + return log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java new file mode 100644 index 0000000000..40de94bd6a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.servlets; + +import org.eclipse.jetty.http.HttpStatus; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class DefaultExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(Exception exception) { + return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500) + .entity(exception.getMessage()) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java index 4215560020..dca41210cc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java @@ -20,20 +20,12 @@ package org.openecomp.sdc.be.servlets; -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -47,14 +39,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** * Root resource (exposed at "/" path) */ @@ -63,107 +55,105 @@ import io.swagger.annotations.ApiResponses; @Api(value = "Distribution Service Servlet", description = "Distribution Service Servlet") @Singleton public class DistributionServiceServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class.getName()); - - @Resource - private DistributionMonitoringBusinessLogic distributionMonitoringLogic; - - @GET - @Path("/services/{serviceUUID}/distribution") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - try { - Either actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId); - - if (actionResponse.isRight()) { - - responseFormat = actionResponse.right().value(); - response = buildErrorResponse(responseFormat); - } else { - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution list for Service"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service"); - log.debug("failed to get service distribution statuses", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - - response = buildErrorResponse(responseFormat); - return response; - } - - } - - @GET - @Path("/services/distribution/{did}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") }) - public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(request); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - ResponseFormat responseFormat = null; - - try { - Either actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId); - - if (actionResponse.isRight()) { - - responseFormat = actionResponse.right().value(); - log.debug("failed to fount statuses for did {} {}", did, responseFormat); - response = buildErrorResponse(responseFormat); - } else { - - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value()); - response = buildOkResponse(responseFormat, actionResponse.left().value()); - - } - - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution Status"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status"); - log.debug("failed to get distribution status ", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - - response = buildErrorResponse(responseFormat); - return response; - } - - } - - private void init(HttpServletRequest request) { - if (distributionMonitoringLogic == null) { - distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext()); - } - } - - private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class); - return distributionBl; - } + private static final Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class); + + @Resource + private DistributionMonitoringBusinessLogic distributionMonitoringLogic; + + @GET + @Path("/services/{serviceUUID}/distribution") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + try { + Either actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId); + + if (actionResponse.isRight()) { + + responseFormat = actionResponse.right().value(); + response = buildErrorResponse(responseFormat); + } else { + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service"); + log.debug("failed to get service distribution statuses", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + + response = buildErrorResponse(responseFormat); + return response; + } + + } + + @GET + @Path("/services/distribution/{did}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") }) + public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(request); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + ResponseFormat responseFormat = null; + + try { + Either actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId); + + if (actionResponse.isRight()) { + + responseFormat = actionResponse.right().value(); + log.debug("failed to fount statuses for did {} {}", did, responseFormat); + response = buildErrorResponse(responseFormat); + } else { + + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value()); + response = buildOkResponse(responseFormat, actionResponse.left().value()); + + } + + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status"); + log.debug("failed to get distribution status ", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + + response = buildErrorResponse(responseFormat); + return response; + } + + } + + private void init(HttpServletRequest request) { + if (distributionMonitoringLogic == null) { + distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext()); + } + } + + private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class); + return distributionBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java index 7a42360355..1a6fb20b46 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java @@ -20,29 +20,11 @@ package org.openecomp.sdc.be.servlets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; +import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,12 +32,9 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.info.ArtifactTypesInfo; -import org.openecomp.sdc.be.model.ArtifactType; -import org.openecomp.sdc.be.model.Category; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.PropertyScope; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.Tag; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.GroupingDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -67,14 +46,17 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Path("/v1/") @@ -89,554 +71,536 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ElementServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ElementServlet.class.getName()); - - /* - ****************************************************************************** - * NEW CATEGORIES category / \ subcategory subcategory / grouping - ******************************************************************************/ - - /* - * - * - * CATEGORIES - */ - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all component categories - @GET - @Path("/categories/{componentType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"), - @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either, ResponseFormat> either = elementBL.getAllCategories(componentType, userId); - if (either.isRight()) { - log.debug("No categories were found for type {}", componentType); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories"); - log.debug("getComponentCategories failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/categories") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either either = elementBL.getAllCategories(userId); - if (either.isRight()) { - log.debug("No categories were found"); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories"); - log.debug("getAllCategories failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @POST - @Path("/category/{componentType}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentCategory( - @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class); - - Either createResourceCategory = elementBL.createCategory(category, componentType, userId); - if (createResourceCategory.isRight()) { - return buildErrorResponse(createResourceCategory.right().value()); - } - - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createResourceCategory.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); - log.debug("createResourceCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId); - - if (createResourceCategory.isRight()) { - return buildErrorResponse(createResourceCategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); - log.debug("createResourceCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - /* - * - * - * SUBCATEGORIES - * - */ - - @POST - @Path("/category/{componentType}/{categoryId}/subCategory") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentSubCategory( - @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class); - - Either createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId); - if (createSubcategory.isRight()) { - return buildErrorResponse(createSubcategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createSubcategory.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create sub-category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category"); - log.debug("createComponentSubCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId, - @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId); - if (deleteSubResourceCategory.isRight()) { - return buildErrorResponse(deleteSubResourceCategory.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component category"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category"); - log.debug("deleteComponentSubCategory failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - /* - * GROUPINGS - */ - @POST - @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), - @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"), - @ApiResponse(code = 500, message = "General Error") }) - public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, - @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, - @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class); - - Either createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId); - if (createGrouping.isRight()) { - return buildErrorResponse(createGrouping.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, createGrouping.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create grouping"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping"); - log.debug("createComponentGrouping failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), - @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) - public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId, - @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId); - if (deleteGrouping.isRight()) { - return buildErrorResponse(deleteGrouping.right().value()); - } - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, null); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component grouping"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping"); - log.debug("deleteGrouping failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all tags - @GET - @Path("/tags") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getTags) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either, ActionStatus> either = elementBL.getAllTags(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No tags were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Tags"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags"); - log.debug("getAllTags failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all property scopes - @GET - @Path("/propertyScopes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getPropertyScopes) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either, ActionStatus> either = elementBL.getAllPropertyScopes(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No property scopes were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property Scopes Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories"); - log.debug("getPropertyScopes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all artifact types - @GET - @Path("/artifactTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET - getArtifactTypes) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either, ActionStatus> either = elementBL.getAllArtifactTypes(userId); - if (either.isRight() || either.left().value() == null) { - log.debug("No artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - - Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - ArtifactTypesInfo typesResponse = new ArtifactTypesInfo(); - typesResponse.setArtifactTypes(either.left().value()); - typesResponse.setHeatDefaultTimeout(defaultHeatTimeout); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); - log.debug("getArtifactTypes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all artifact types - @GET - @Path("/configuration/ui") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getConfiguration) Start handle request of {}", url); - - try { - ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); - Either, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId); - Either defaultHeatTimeout = elementBL.getDefaultHeatTimeout(); - Either, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes(); - Either, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap(); - - if (otherEither.isRight() || otherEither.left().value() == null) { - log.debug("No other artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) { - log.debug("No deployment artifact types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) { - log.debug("heat default timeout was not found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) { - log.debug("No resource types were found"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); - } else { - Map artifacts = new HashMap(); - Map configuration = new HashMap(); - - artifacts.put("other", otherEither.left().value()); - artifacts.put("deployment", deploymentEither.left().value()); - configuration.put("artifacts", artifacts); - configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value()); - configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames()); - configuration.put("roles", elementBL.getAllSupportedRoles()); - configuration.put("resourceTypes", resourceTypesMap.left().value()); - configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration); - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); - log.debug("getArtifactTypes failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all followed resources and services - @GET - @Path("/followed") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Response res = null; - User userData = null; - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - // Getting the user - Either either = userAdminManager.getUser(userId, false); - if (either.isRight()) { - // Couldn't find or otherwise fetch the user - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } - - if (either.left().value() != null) { - userData = either.left().value(); - Either>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData); - // res = - // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - // followedResourcesServices.left().value()); - if (followedResourcesServices.isRight()) { - log.debug("failed to get followed resources services "); - return buildErrorResponse(followedResourcesServices.right().value()); - } - Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value()); - res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); - } else { - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Followed Resources / Services Categories"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories"); - log.debug("Getting followed resources/services failed with exception", e); - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return res; - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all certified resources and services and their last version - @GET - @Path("/screen") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List excludeTypes) { - - Response res = null; - try { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Either>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes); - - if (catalogData.isRight()) { - log.debug("failed to get catalog data"); - return buildErrorResponse(catalogData.right().value()); - } - Object data = RepresentationUtils.toRepresentation(catalogData.left().value()); - res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Catalog Components"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components"); - log.debug("Getting catalog components failed with exception", e); - res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return res; - } - - @DELETE - @Path("/inactiveComponents/{componentType}") - public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType); - if (nodeType == null) { - log.info("componentType is not valid: {]", componentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - - List componentsList = new ArrayList(); - componentsList.add(nodeType); - try { - ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context); - Map, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList); - Either, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType); - - if (cleanResult.isRight()) { - log.debug("failed to delete marked components of type {}", nodeType); - response = buildErrorResponse(cleanResult.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Marked Components"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components"); - log.debug("delete marked components failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/ecompPortalMenu") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve ONAP portal menu - MOC", httpMethod = "GET", notes = "Retrieve ONAP portal menu", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ONAP portal menu") }) - public Response getListOfCsars(@Context final HttpServletRequest request) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]"); - } + private static final Logger log = LoggerFactory.getLogger(ElementServlet.class); + + /* + ****************************************************************************** + * NEW CATEGORIES category / \ subcategory subcategory / grouping + ******************************************************************************/ + + /* + * + * + * CATEGORIES + */ + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all component categories + @GET + @Path("/categories/{componentType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"), + @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either, ResponseFormat> either = elementBL.getAllCategories(componentType, userId); + if (either.isRight()) { + log.debug("No categories were found for type {}", componentType); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories"); + log.debug("getComponentCategories failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/categories") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either either = elementBL.getAllCategories(userId); + if (either.isRight()) { + log.debug("No categories were found"); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories"); + log.debug("getAllCategories failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @POST + @Path("/category/{componentType}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentCategory( + @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class); + + Either createResourceCategory = elementBL.createCategory(category, componentType, userId); + if (createResourceCategory.isRight()) { + return buildErrorResponse(createResourceCategory.right().value()); + } + + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createResourceCategory.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); + log.debug("createResourceCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId); + + if (createResourceCategory.isRight()) { + return buildErrorResponse(createResourceCategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category"); + log.debug("createResourceCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + /* + * + * + * SUBCATEGORIES + * + */ + + @POST + @Path("/category/{componentType}/{categoryId}/subCategory") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentSubCategory( + @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class); + + Either createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId); + if (createSubcategory.isRight()) { + return buildErrorResponse(createSubcategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createSubcategory.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category"); + log.debug("createComponentSubCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId, + @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId); + if (deleteSubResourceCategory.isRight()) { + return buildErrorResponse(deleteSubResourceCategory.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category"); + log.debug("deleteComponentSubCategory failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + /* + * GROUPINGS + */ + @POST + @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category") + @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"), + @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"), + @ApiResponse(code = 500, message = "General Error") }) + public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, + @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId, + @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class); + + Either createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId); + if (createGrouping.isRight()) { + return buildErrorResponse(createGrouping.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, createGrouping.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping"); + log.debug("createComponentGrouping failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"), + @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") }) + public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId, + @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId); + if (deleteGrouping.isRight()) { + return buildErrorResponse(deleteGrouping.right().value()); + } + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, null); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping"); + log.debug("deleteGrouping failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all tags + @GET + @Path("/tags") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getTags) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either, ActionStatus> either = elementBL.getAllTags(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No tags were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags"); + log.debug("getAllTags failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all property scopes + @GET + @Path("/propertyScopes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getPropertyScopes) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either, ActionStatus> either = elementBL.getAllPropertyScopes(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No property scopes were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories"); + log.debug("getPropertyScopes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all artifact types + @GET + @Path("/artifactTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET - getArtifactTypes) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either, ActionStatus> either = elementBL.getAllArtifactTypes(userId); + if (either.isRight() || either.left().value() == null) { + log.debug("No artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + + Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + ArtifactTypesInfo typesResponse = new ArtifactTypesInfo(); + typesResponse.setArtifactTypes(either.left().value()); + typesResponse.setHeatDefaultTimeout(defaultHeatTimeout); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); + log.debug("getArtifactTypes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all artifact types + @GET + @Path("/configuration/ui") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getConfiguration) Start handle request of {}", url); + + try { + ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext()); + Either, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId); + Either defaultHeatTimeout = elementBL.getDefaultHeatTimeout(); + Either, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes(); + Either, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap(); + + if (otherEither.isRight() || otherEither.left().value() == null) { + log.debug("No other artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) { + log.debug("No deployment artifact types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) { + log.debug("heat default timeout was not found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) { + log.debug("No resource types were found"); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT)); + } else { + Map artifacts = new HashMap(); + Map configuration = new HashMap(); + + artifacts.put("other", otherEither.left().value()); + artifacts.put("deployment", deploymentEither.left().value()); + configuration.put("artifacts", artifacts); + configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value()); + configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames()); + configuration.put("roles", elementBL.getAllSupportedRoles()); + configuration.put("resourceTypes", resourceTypesMap.left().value()); + configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types"); + log.debug("getArtifactTypes failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all followed resources and services + @GET + @Path("/followed") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Response res = null; + User userData = null; + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + // Getting the user + Either either = userAdminManager.getUser(userId, false); + if (either.isRight()) { + // Couldn't find or otherwise fetch the user + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } + + if (either.left().value() != null) { + userData = either.left().value(); + Either>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData); + if (followedResourcesServices.isRight()) { + log.debug("failed to get followed resources services "); + return buildErrorResponse(followedResourcesServices.right().value()); + } + Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value()); + res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); + } else { + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories"); + log.debug("Getting followed resources/services failed with exception", e); + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return res; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all certified resources and services and their last version + @GET + @Path("/screen") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List excludeTypes) { + + Response res = null; + try { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Either>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId); + + if (catalogData.isRight()) { + log.debug("failed to get catalog data"); + return buildErrorResponse(catalogData.right().value()); + } + Object data = RepresentationUtils.toRepresentation(catalogData.left().value()); + res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components"); + log.debug("Getting catalog components failed with exception", e); + res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return res; + } + + @DELETE + @Path("/inactiveComponents/{componentType}") + public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType); + if (nodeType == null) { + log.info("componentType is not valid: {]", componentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + + List componentsList = new ArrayList(); + componentsList.add(nodeType); + try { + ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context); + Map, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList); + Either, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType); + + if (cleanResult.isRight()) { + log.debug("failed to delete marked components of type {}", nodeType); + response = buildErrorResponse(cleanResult.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components"); + log.debug("delete marked components failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/ecompPortalMenu") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve ecomp portal menu - MOC", httpMethod = "GET", notes = "Retrieve ecomp portal menu", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ecomp portal menu") }) + public Response getListOfCsars(@Context final HttpServletRequest request) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java index 22391bbdc1..100fd36e27 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java @@ -20,22 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.common.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -50,199 +42,217 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; /** * Root resource (exposed at "/" path) */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) @Path("/v1/catalog") -@Api(value = "Resource Group Servlet", description = "Resource Group Servlet") +@Api(value = "Resource Group Servlet") @Singleton public class GroupServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(GroupServlet.class.getName()); - - private Gson gson = new Gson(); - - @GET - @Path("/{containerComponentType}/{componentId}/groups/{groupId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Group not found") }) - public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - try { - - GroupBusinessLogic businessLogic = this.getGroupBL(context); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = businessLogic - .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract {}", containerComponentType); - return buildErrorResponse(actionResponse.right().value()); - } - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - actionResponse.left().value()); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); - log.debug("getGroupArtifactById unexpected exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - @PUT - @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupMetadata( - @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @ApiParam(value = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User user = new User(); - user.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - GroupBusinessLogic businessLogic = getGroupBL(context); - - Either convertResponse = parseToObject(data, () -> GroupDefinition.class); - if (convertResponse.isRight()) { - log.debug("failed to parse group"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - GroupDefinition updatedGroup = convertResponse.left().value(); - - // Update GroupDefinition - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either actionResponse = businessLogic - .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true); - - if (actionResponse.isRight()) { - log.debug("failed to update GroupDefinition"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - GroupDefinition group = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(group); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata"); - log.debug("update group metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /** - * Updates List of properties on a group (only values) - * @param containerComponentType - * @param componentId - * @param groupUniqueId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, - @ApiParam(value = "Service object to be Updated", required = true) String data, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - init(log); - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User user = new User(); - user.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - GroupBusinessLogic businessLogic = getGroupBL(context); - Either, ResponseFormat> convertResponse = parseListOfObjects(data, - new TypeToken>() { - }.getType()); - - if (convertResponse.isRight()) { - log.debug("failed to parse group Property"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - List groupPropertyToUpdate = convertResponse.left().value(); - - // Update GroupDefinition - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); - Either, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties( - componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false); - - if (actionResponse.isRight()) { - log.debug("failed to update GroupDefinition"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - List groupProperty = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(groupProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties"); - log.debug("update group properties failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } + private static final Logger log = LoggerFactory.getLogger(GroupServlet.class); + public static final String START_HANDLE_REQUEST = "Start handle request of {}"; + + @POST + @Path("/{containerComponentType}/{componentId}/groups/{groupType}") + @ApiOperation(value = "Create group ", httpMethod = "POST", notes = "Creates new group in component and returns it", response = GroupDefinition.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Group created"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Component not found"), + @ApiResponse(code = 500, message = "Internal Error") + }) + public Response createGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupType") final String type, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(post) Start handle request of {}", url); + + GroupBusinessLogic businessLogic = getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition groupDefinition = businessLogic + .createGroup(type, componentTypeEnum, componentId, userId); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), + groupDefinition); + } + + @GET + @Path("/{containerComponentType}/{componentId}/groups/{groupId}") + @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "group found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Group not found")}) + public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + try { + + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either actionResponse = businessLogic + .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract {}", containerComponentType); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + actionResponse.left().value()); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById"); + log.debug("getGroupArtifactById unexpected exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}") + @ApiOperation(value = "Delete Group", httpMethod = "DELETE", notes = "Returns deleted group id", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "ResourceInstance deleted"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Component not found"), + @ApiResponse(code = 500, message = "Internal Error") + }) + public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupUniqueId") final String groupId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(START_HANDLE_REQUEST, url); + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition groupDefinition = businessLogic + .deleteGroup(componentTypeEnum, componentId, groupId, userId); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId()); + } + + @PUT + @Path("/{containerComponentType}/{componentId}/groups/{groupId}") + @ApiOperation(value = "Update Group metadata", httpMethod = "PUT", notes = "Returns updated Group", response = Response.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Group updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / group Not found")}) + public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @PathParam("groupId") final String groupId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "GroupDefinition", required = true) GroupDefinition groupData, + @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + GroupBusinessLogic businessLogic = this.getGroupBL(context); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + GroupDefinition updatedGroup = businessLogic.updateGroup(componentTypeEnum, componentId, groupId, userId, groupData); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup); + } + + /** + * Updates List of properties on a group (only values) + * @param containerComponentType + * @param componentId + * @param groupUniqueId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties") + @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId, + @ApiParam(value = "Group Properties to be Updated", required = true) String data, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + init(log); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(START_HANDLE_REQUEST, url); + + User user = new User(); + user.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + GroupBusinessLogic businessLogic = getGroupBL(context); + Either, ResponseFormat> convertResponse = parseListOfObjects(data, + new TypeToken>() { + }.getType()); + + if (convertResponse.isRight()) { + log.debug("failed to parse group Property"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + List groupPropertyToUpdate = convertResponse.left().value(); + + // Update GroupDefinition + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + Either, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties( + componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false); + + if (actionResponse.isRight()) { + log.debug("failed to update GroupDefinition"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + List groupProperty = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(groupProperty); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties"); + log.debug("update group properties failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java new file mode 100644 index 0000000000..a056b1d454 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; +import org.openecomp.sdc.be.mixin.GroupTypeMixin; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.view.ResponseView; +import org.openecomp.sdc.common.api.Constants; +import org.springframework.stereotype.Controller; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "group types resource") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class GroupTypesEndpoint { + + private final GroupTypeBusinessLogic groupTypeBusinessLogic; + + public GroupTypesEndpoint(GroupTypeBusinessLogic groupTypeBusinessLogic) { + this.groupTypeBusinessLogic = groupTypeBusinessLogic; + } + + @GET + @Path("/groupTypes") + @ApiOperation(value = "Get group types ", httpMethod = "GET", notes = "Returns group types", response = GroupTypeDefinition.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "group types found"), + @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 500, message = "Internal Error") + }) + @ResponseView(mixin = {GroupTypeMixin.class}) + public List getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed") + @QueryParam("internalComponentType") String internalComponentType) { + return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java index 4de5488351..1d627e6fd3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java @@ -20,25 +20,14 @@ package org.openecomp.sdc.be.servlets; -import java.util.List; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.InputsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -58,398 +47,309 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) -@Path("/v1/catalog") @Api(value = "Input Catalog", description = "Input Servlet") +@Path("/v1/catalog") @Singleton +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) public class InputsServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName()); - - @GET - @Path("/services/{componentId}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @QueryParam("fromId") String fromName, - @QueryParam("amount") int amount, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - - InputsBusinessLogic businessLogic = getInputBL(context); - - Either, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, componentId, fromName, amount); - if (inputsResponse.isRight()) { - log.debug("failed to get inputs {}", componentType); - return buildErrorResponse(inputsResponse.right().value()); - } - Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); - log.debug("getInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - @POST - @Path("/{containerComponentType}/{componentId}/update/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateComponentInputs( - @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, - @PathParam("componentId") final String componentId, - @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) { - - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - String userId = request.getHeader(Constants.USER_ID_HEADER); - - try { - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);; - if(inputEither.isRight()){ - log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value()); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - InputDefinition input = inputEither.left().value(); - - log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", input); - - ServletContext context = request.getSession().getServletContext(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); - - InputsBusinessLogic businessLogic = getInputBL(context); - if (businessLogic == null) { - log.debug("Unsupported component type {}", containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); - } - - Either actionResponse = businessLogic.updateInputValue(componentType, componentId, input, userId, true, false); - - if (actionResponse.isRight()) { - return buildErrorResponse(actionResponse.right().value()); - } - - InputDefinition resourceInstanceProperty = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(resourceInstanceProperty); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - log.error("create and associate RI failed with exception: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - - @GET - @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, - @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId); - if (inputsResponse.isRight()) { - log.debug("failed to get component instance inputs {}", componentType); - return buildErrorResponse(inputsResponse.right().value()); - } - Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); - log.debug("getInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, - @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(GET) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); - if (inputPropertiesRes.isRight()) { - log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId); - return buildErrorResponse(inputPropertiesRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get properties by input id {}, for component instance {} ", inputId, instanceId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId); - log.debug("getInputPropertiesForComponentInstance failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId); - - if (inputsRes.isRight()) { - log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); - return buildErrorResponse(inputsRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); - log.debug("getInputsForComponentInput failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/{componentType}/{componentId}/inputs/{inputId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - Either inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); - - if (inputsRes.isRight()) { - log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); - return buildErrorResponse(inputsRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); - log.debug("getInputsForComponentInput failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - public Either parseToComponentInstanceMap(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - - @POST - @Path("/{componentType}/{componentId}/create/inputs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier); - if (componentInstInputsMapRes.isRight()) { - log.debug("failed to parse componentInstInputsMap"); - response = buildErrorResponse(componentInstInputsMapRes.right().value()); - return response; - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value(); - - Either, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); - if (inputPropertiesRes.isRight()) { - log.debug("failed to create inputs for service: {}", componentId); - return buildErrorResponse(inputPropertiesRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create inputs for service with id: {}", componentId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); - log.debug("createMultipleInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - - @DELETE - @Path("/{componentType}/{componentId}/delete/{inputId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) - public Response deleteInput ( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("inputId") final String inputId, + private static final Logger log = LoggerFactory.getLogger(InputsServlet.class); + + @POST + @Path("/{containerComponentType}/{componentId}/update/inputs") + @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateComponentInputs( + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("componentId") final String componentId, + @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + String userId = request.getHeader(Constants.USER_ID_HEADER); + + try { + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either inputsEither = getComponentsUtils() + .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class, + AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE); + if(inputsEither.isRight()){ + log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value()); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + List inputsToUpdate = Arrays.asList(inputsEither.left().value()); + + log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate); + + ServletContext context = request.getSession().getServletContext(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType); + + InputsBusinessLogic businessLogic = getInputBL(context); + if (businessLogic == null) { + log.debug("Unsupported component type {}", containerComponentType); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR)); + } + + Either, ResponseFormat> actionResponse = businessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false); + + if (actionResponse.isRight()) { + return buildErrorResponse(actionResponse.right().value()); + } + + List componentInputs = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(componentInputs); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } + catch (Exception e) { + log.error("create and associate RI failed with exception: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + @GET + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs") + @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, + @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId); + if (inputsResponse.isRight()) { + log.debug("failed to get component instance inputs {}", componentType); + return buildErrorResponse(inputsResponse.right().value()); + } + Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType); + log.debug("getInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties") + @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId, + @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(GET) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId); + if (inputPropertiesRes.isRight()) { + log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId); + return buildErrorResponse(inputPropertiesRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId); + log.debug("getInputPropertiesForComponentInstance failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs") + @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId); + + if (inputsRes.isRight()) { + log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); + return buildErrorResponse(inputsRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); + log.debug("getInputsForComponentInput failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/{componentType}/{componentId}/inputs/{inputId}") + @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + Either inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false); + + if (inputsRes.isRight()) { + log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId); + return buildErrorResponse(inputsRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId); + log.debug("getInputsForComponentInput failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private Either parseToComponentInstanceMap(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + } + + @POST + @Path("/{componentType}/{componentId}/create/inputs") + @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Either componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier); + if (componentInstInputsMapRes.isRight()) { + log.debug("failed to parse componentInstInputsMap"); + response = buildErrorResponse(componentInstInputsMapRes.right().value()); + return response; + } + + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value(); + + Either, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); + if (inputPropertiesRes.isRight()) { + log.debug("failed to create inputs for service: {}", componentId); + return buildErrorResponse(inputPropertiesRes.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); + log.debug("createMultipleInputs failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + + @DELETE + @Path("/{componentType}/{componentId}/delete/{inputId}/input") + @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) + public Response deleteInput ( + @PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - Either deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); - if (deleteInput.isRight()){ - ResponseFormat deleteResponseFormat = deleteInput.right().value(); - response = buildErrorResponse(deleteResponseFormat); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); - } catch (Exception e){ - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); - log.debug("Delete input failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - - - /*@PUT - @Path("/{componentType}/{componentId}/edit/{inputId}/input") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") }) - public Response editInputValue ( - @PathParam("componentType") final String componentType, - @PathParam("componentId") final String componentId, - @PathParam("inputId") final String inputId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - Either deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId); - if (deleteInput.isRight()){ - ResponseFormat deleteResponseFormat = deleteInput.right().value(); - response = buildErrorResponse(deleteResponseFormat); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); - } catch (Exception e){ - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); - log.debug("Delete input failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - }*/ - - protected InputsBusinessLogic getInputBL(ServletContext context) { - - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - InputsBusinessLogic inputsBusinessLogic = webApplicationContext.getBean(InputsBusinessLogic.class); - return inputsBusinessLogic; - } + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + InputsBusinessLogic businessLogic = getInputBL(context); + Either deleteInput = businessLogic.deleteInput(componentId, userId, inputId); + if (deleteInput.isRight()){ + ResponseFormat deleteResponseFormat = deleteInput.right().value(); + response = buildErrorResponse(deleteResponseFormat); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value()); + } catch (Exception e){ + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId); + log.debug("Delete input failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private InputsBusinessLogic getInputBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(InputsBusinessLogic.class); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java index c2d7c2a6a1..5720c56c38 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java @@ -20,20 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.codehaus.jackson.map.ObjectMapper; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; @@ -52,145 +42,115 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet") @Singleton public class LifecycleServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(LifecycleServlet.class.getName()); - - @POST - @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") }) - public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo, - @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," - + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection, - @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, - @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request, - @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - LifecycleBusinessLogic businessLogic = getLifecycleBL(context); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Response response = null; - - // get modifier from graph - log.debug("get modifier properties"); - Either eitherGetUser = getUser(request, userId); - if (eitherGetUser.isRight()) { - return buildErrorResponse(eitherGetUser.right().value()); - } - User user = eitherGetUser.left().value(); - - String resourceIdLower = componentId.toLowerCase(); - log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower); - Either validateEnum = validateTransitionEnum(lifecycleTransition, user); - if (validateEnum.isRight()) { - return validateEnum.right().value(); - } - - LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); - - try { - if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { - // Either changeInfoResult - // = - // getComponentsUtils().convertJsonToObjectUsingObjectMapper(jsonChangeInfo, - // user, LifecycleChangeInfo.class, - // AuditingActionEnum.CHECKOUT_RESOURCE, null); - ObjectMapper mapper = new ObjectMapper(); - changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); - } - } - - catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject"); - BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); - log.debug("failed to convert from json {}", jsonChangeInfo, e); - ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return buildErrorResponse(responseFormat); - } - - try { - LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); - ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); - if (componentType != null) { - Either actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); - - if (actionResponse.isRight()) { - log.info("failed to change resource state"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - log.debug("change state successful !!!"); - UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); - Object value = RepresentationUtils.toRepresentation(componentMetatdata); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); - return response; - } else { - log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, - ComponentTypeEnum.PRODUCT_PARAM_NAME); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return buildErrorResponse(error); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); - log.debug("change lifecycle state failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - private Either validateTransitionEnum(final String lifecycleTransition, User user) { - LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; - try { - transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); - } catch (IllegalArgumentException e) { - log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString()); - ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE); - return Either.right(buildErrorResponse(error)); - } - return Either.left(transitionEnum); - } - -// private LifecycleBusinessLogic getLifecycleBL(ServletContext context) { -// WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); -// WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); -// LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class); -// return resourceBl; -// } -// -// protected Either getUser(final HttpServletRequest request, String userId) { -// -// Either eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false); -// if (eitherCreator.isRight()) { -// log.info("createResource method - user is not listed. userId= {}", userId); -// ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION); -// User user = new User("", "", userId, "", null, null); -// -// getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null); -// return Either.right(buildErrorResponse(errorResponse)); -// } -// return Either.left(eitherCreator.left().value()); -// -// } + private static final Logger log = LoggerFactory.getLogger(LifecycleServlet.class); + + @POST + @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") }) + public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo, + @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection, + @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition, + @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request, + @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + LifecycleBusinessLogic businessLogic = getLifecycleBL(context); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Response response = null; + + // get modifier from graph + log.debug("get modifier properties"); + Either eitherGetUser = getUser(request, userId); + if (eitherGetUser.isRight()) { + return buildErrorResponse(eitherGetUser.right().value()); + } + User user = eitherGetUser.left().value(); + + String resourceIdLower = componentId.toLowerCase(); + log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower); + Either validateEnum = validateTransitionEnum(lifecycleTransition, user); + if (validateEnum.isRight()) { + return validateEnum.right().value(); + } + + LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(); + + try { + if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) { + ObjectMapper mapper = new ObjectMapper(); + changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks()); + } + } + + catch (Exception e) { + BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject"); + log.debug("failed to convert from json {}", jsonChangeInfo, e); + ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return buildErrorResponse(responseFormat); + } + + try { + LifeCycleTransitionEnum transitionEnum = validateEnum.left().value(); + ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection); + if (componentType != null) { + Either actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true); + + if (actionResponse.isRight()) { + log.info("failed to change resource state"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + log.debug("change state successful !!!"); + UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); + Object value = RepresentationUtils.toRepresentation(componentMetatdata); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); + return response; + } else { + log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, + ComponentTypeEnum.PRODUCT_PARAM_NAME); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE); + return buildErrorResponse(error); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State"); + log.debug("change lifecycle state failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private Either validateTransitionEnum(final String lifecycleTransition, User user) { + LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT; + try { + transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition); + } catch (IllegalArgumentException e) { + log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e); + ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE); + return Either.right(buildErrorResponse(error)); + } + return Either.left(transitionEnum); + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java new file mode 100644 index 0000000000..b6e15cef9a --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java @@ -0,0 +1,307 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + + +import org.openecomp.sdc.be.model.PolicyTargetDTO; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Provides REST API to create, retrieve, update, delete a policy + */ +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "Policy Servlet") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PolicyServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(PolicyServlet.class); + private final PolicyBusinessLogic policyBusinessLogic; + + public PolicyServlet(PolicyBusinessLogic policyBusinessLogic, ServletUtils servletUtils, ResourceImportManager resourceImportManager, ComponentsUtils componentsUtils) { + this.policyBusinessLogic = policyBusinessLogic; + this.servletUtils = servletUtils; + this.resourceImportManager = resourceImportManager; + this.componentsUtils = componentsUtils; + } + + @POST + @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}") + @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Policy already exist"), @ApiResponse(code = 404, message = "Component not found")}) + public Response createPolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyTypeName") final String policyTypeName, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + try { + Wrapper componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true) + .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l), + this::buildErrorResponse)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy"); + log.error("Failed to create policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response updatePolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + try { + Wrapper componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + Wrapper policyWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper); + if (policyWrapper.isEmpty()) { + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } + if (!policyWrapper.isEmpty()) { + policyWrapper.getInnerElement().setUniqueId(policyId); + responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true) + .either(this::buildOkResponse, + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy"); + log.error("Failed to update policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @GET + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response getPolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + try { + Wrapper componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId) + .either(this::buildOkResponse, + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy"); + log.error("Failed to retrieve policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @DELETE + @Path("/{containerComponentType}/{componentId}/policies/{policyId}") + @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response deletePolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(log); + + Wrapper responseWrapper = new Wrapper<>(); + try { + Wrapper componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true) + .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null), + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy"); + log.error("Failed to delete policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + @GET + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") + @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Properties found"),@ApiResponse(code = 400, message = "invalid content - Error: containerComponentType is invalid"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Componentorpolicy not found"), + @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.") })public Response getPolicyProperties(@ApiParam(value = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId, + @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @Context final HttpServletRequest request) { + init(log); + try { + return convertToComponentType(containerComponentType) + .left() + .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId)) + .either(this::buildOkResponse, + this::buildErrorResponse); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties"); + log.debug("#getPolicyProperties - get Policy properties has failed.", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") + @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) { + init(log); + Wrapper responseWrapper = new Wrapper<>(); + try { + Wrapper componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + Wrapper propertiesWrapper = new Wrapper<>(); + if (responseWrapper.isEmpty()) { + convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper); + if (propertiesWrapper.isEmpty()) { + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); + } + } + if (!propertiesWrapper.isEmpty()) { + responseWrapper.setInnerElement( + policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true) + .either(this::buildOkResponse, this::buildErrorResponse)); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy"); + log.error("Failed to update policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + + private Wrapper validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper responseWrapper) { + Wrapper componentTypeWrapper = new Wrapper<>(); + if (StringUtils.isEmpty(userId)) { + log.error("Missing userId HTTP header. "); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID))); + } + if (responseWrapper.isEmpty()) { + validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType); + } + return componentTypeWrapper; + } + + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update policy targets", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")}) + public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request, + List requestJson) { + try { + + Map> policyTarget = convertTargetDTOToBLTarget(requestJson); + if(policyTarget == null){ + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, StringUtils.join(requestJson.stream().map(PolicyTargetDTO::getType).collect(Collectors.toList())), ",")); + } + + return convertToComponentType(containerComponentType) + .left() + .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId)) + .either(this::buildOkResponse, + this::buildErrorResponse); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy"); + log.debug("Policy creation has been failed with the exception{}. ", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + + private Map> convertTargetDTOToBLTarget(List targetDTOList) { + Map> policyTarget = new HashMap<>(); + for (PolicyTargetDTO currentTarget : targetDTOList) { + if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){ + return null; + } + } + return policyTarget; + } + public boolean addTargetsByType(Map> policyTarget, String type, List uniqueIds) { + PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type); + if(targetTypeEnum != null){ + policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds)); + return true; + } + else{ + return false; + } + } + + private List validateUniquenessOfIds(List uniqueIds) { + return uniqueIds.stream().distinct().collect(Collectors.toList()); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java new file mode 100644 index 0000000000..aa4bfa87c7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.mixin.PolicyTypeMixin; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.view.ResponseView; +import org.openecomp.sdc.common.api.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "policy types resource") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class PolicyTypesEndpoint extends BeGenericServlet{ + + private static final Logger log = LoggerFactory.getLogger(PolicyTypesEndpoint.class); + + private final PolicyTypeBusinessLogic policyTypeBusinessLogic; + + public PolicyTypesEndpoint(PolicyTypeBusinessLogic policyTypeBusinessLogic) { + this.policyTypeBusinessLogic = policyTypeBusinessLogic; + } + + @GET + @Path("/policyTypes") + @ApiOperation(value = "Get policy types ", httpMethod = "GET", notes = "Returns policy types", response = PolicyTypeDefinition.class, responseContainer="List") + @ApiResponses(value = { @ApiResponse(code = 200, message = "policy types found"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.")}) + @ResponseView(mixin = {PolicyTypeMixin.class}) + public Response getPolicyTypes(@ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed") + @QueryParam("internalComponentType") String internalComponentType, + @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + log.debug("(get) Start handle request of GET policyTypes"); + try { + return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType) + .either(this::buildOkResponse, + this::buildErrorResponse); + } catch (Exception e) { + log.error("#getPolicyTypes - Exception occurred during get policy types", e); + return buildGeneralErrorResponse(); + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java index c0c987b78a..05ece30535 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java @@ -20,24 +20,9 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,262 +34,256 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Product Catalog", description = "Product Servlet") @Singleton public class ProductServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName()); - - @POST - @Path("/products") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"), - @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") }) - public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - Product product = RepresentationUtils.fromRepresentation(data, Product.class); - Either actionResponse = businessLogic.createProduct(product, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to create product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Product"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product"); - log.debug("create product failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/{productId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"), - @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), }) - public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ProductBusinessLogic businessLogic = getProductBL(context); - log.trace("get product with id {}", productId); - Either actionResponse = businessLogic.getProduct(productId, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to get product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Product"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product"); - log.debug("get product failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/productName/{productName}/productVersion/{productVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") }) - public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - Either actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Product product = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(product); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get product by name and version"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version"); - log.debug("get product failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @DELETE - @Path("/products/{productId}") - public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ProductBusinessLogic businessLogic = getProductBL(context); - log.trace("delete product with id {}", productId); - Either actionResponse = businessLogic.deleteProduct(productId, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to delete product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with error ", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/products/{productId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - - try { - String productIdLower = productId.toLowerCase(); - ProductBusinessLogic businessLogic = getProductBL(context); - Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class); - Either actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to update product"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Product product = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(product); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Product Metadata"); - log.debug("update product metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/products/validate-name/{productName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - try { - ProductBusinessLogic businessLogic = getProductBL(context); - - Either, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get validate service name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name"); - log.debug("validate product name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + private static final Logger log = LoggerFactory.getLogger(ProductServlet.class); + + @POST + @Path("/products") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"), + @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") }) + public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + Product product = RepresentationUtils.fromRepresentation(data, Product.class); + Either actionResponse = businessLogic.createProduct(product, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to create product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product"); + log.debug("create product failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/{productId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"), + @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), }) + public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ProductBusinessLogic businessLogic = getProductBL(context); + log.trace("get product with id {}", productId); + Either actionResponse = businessLogic.getProduct(productId, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to get product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product"); + log.debug("get product failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/productName/{productName}/productVersion/{productVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") }) + public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + Either actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Product product = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(product); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version"); + log.debug("get product failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @DELETE + @Path("/products/{productId}") + public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ProductBusinessLogic businessLogic = getProductBL(context); + log.trace("delete product with id {}", productId); + Either actionResponse = businessLogic.deleteProduct(productId, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to delete product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object product = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with error ", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/products/{productId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + + try { + String productIdLower = productId.toLowerCase(); + ProductBusinessLogic businessLogic = getProductBL(context); + Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class); + Either actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to update product"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Product product = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(product); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + log.debug("update product metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/products/validate-name/{productName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + try { + ProductBusinessLogic businessLogic = getProductBL(context); + + Either, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get validate service name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name"); + log.debug("validate product name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java index bc5ad35c8f..14d2628926 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java @@ -20,29 +20,12 @@ package org.openecomp.sdc.be.servlets; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @@ -64,383 +47,326 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resource Property Servlet", description = "Resource Property Servlet") @Singleton public class PropertyServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(PropertyServlet.class.getName()); - - @POST - @Path("resources/{resourceId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource property already exist") }) - public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); - - try { - // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry entry = properties.entrySet().iterator().next(); - String propertyName = entry.getKey(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // create the new property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to create Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData property = status.left().value(); - String name = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property"); - log.debug("create property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @GET - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}, modifier id is {}", url, userId); - - try { - - // - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId); - - if (status.isRight()) { - log.info("Failed to get Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry property = status.left().value(); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); - log.debug("get property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @DELETE - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userId); - - try { - - // delete the property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); - if (status.isRight()) { - log.debug("Failed to delete Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry property = status.left().value(); - String name = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property"); - log.debug("delete property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @PUT - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - try { - // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry entry = properties.entrySet().iterator().next(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // update property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to update Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData property = status.left().value(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Property"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property"); - log.debug("update property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - private Either, ActionStatus> getPropertyModel(String resourceId, String data) { - JSONParser parser = new JSONParser(); - JSONObject root; - try { - Map properties = new HashMap(); - root = (JSONObject) parser.parse(data); - - Set entrySet = root.entrySet(); - Iterator iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Entry next = (Entry) iterator.next(); - String propertyName = (String) next.getKey(); - JSONObject value = (JSONObject) next.getValue(); - String jsonString = value.toJSONString(); - Either convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); - if (convertJsonToObject.isRight()) { - return Either.right(convertJsonToObject.right().value()); - } - PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); - // PropertyDefinition propertyDefinition = - // gson.fromJson(jsonString , PropertyDefinition.class); - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); - propertyDefinition.setUniqueId(uniqueId); - properties.put(propertyName, propertyDefinition); - } - - // Set keySet = root.keySet(); - // for (Object propertyName : keySet){ - // JSONObject val = (JSONObject) root.get(propertyName); - // String jsonString = val.toJSONString(); - // Either convertJsonToObject = - // convertJsonToObject(jsonString, PropertyDefinition.class); - // if (convertJsonToObject.isRight()){ - // return Either.right(convertJsonToObject.right().value()); - // } - // PropertyDefinition propertyDefinition = - // convertJsonToObject.left().value(); - // //PropertyDefinition propertyDefinition = - // gson.fromJson(jsonString , PropertyDefinition.class); - // String uniqueId = - // UniqueIdBuilder.buildPropertyUniqueId("resourceId", - // (String)propertyName); - // propertyDefinition.setUniqueId(uniqueId); - // properties.put((String)propertyName,propertyDefinition); - // } - return Either.left(properties); - } catch (ParseException e) { - log.info("Property conetnt is invalid - {}", data); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } - - private String propertyToJson(Map.Entry property) { - JSONObject root = new JSONObject(); - String propertyName = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - // String jsonPropertyDefinition = gson.toJson(propertyDefinition); - // root.put(propertyName, jsonPropertyDefinition); - JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); - root.put(propertyName, propertyDefinitionO); - propertyDefinition.getType(); - return root.toString(); - } - - private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { - - Either either = convertObjectToJson(propertyDefinition); - if (either.isRight()) { - return new JSONObject(); - } - String value = either.left().value(); - try { - JSONObject root = (JSONObject) new JSONParser().parse(value); - return root; - } catch (ParseException e) { - log.info("failed to convert input to json"); - log.debug("failed to convert to json", e); - return new JSONObject(); - } - - } - - private Either convertJsonToObject(String data, Class clazz) { - T t = null; - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - try { - log.trace("convert json to object. json=\n {}", data); - t = gson.fromJson(data, clazz); - if (t == null) { - log.info("object is null after converting from json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert from json"); - log.debug("failed to convert from json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(t); - } - - private Either convertObjectToJson(PropertyDefinition propertyDefinition) { - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); - try { - log.trace("convert object to json. propertyDefinition= {}", propertyDefinition.toString()); - String json = gson.toJson(propertyDefinition); - if (json == null) { - log.info("object is null after converting to json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(json); - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert to json"); - log.debug("failed to convert fto json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - - } - - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); - return propertytBl; - } - - // private class UiProperty{ - // String type; - // String source; - // String name; - // String description; - // public String getType() { - // return type; - // } - // public void setType(String type) { - // this.type = type; - // } - // public String getSource() { - // return source; - // } - // public void setSource(String source) { - // this.source = source; - // } - // public String getName() { - // return name; - // } - // public void setName(String name) { - // this.name = name; - // } - // public String getDescription() { - // return description; - // } - // public void setDescription(String description) { - // this.description = description; - // } - // - // } + private static final Logger log = LoggerFactory.getLogger(PropertyServlet.class); + + @POST + @Path("resources/{resourceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource property already exist") }) + public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data); + + try { + // convert json to PropertyDefinition + Either, ActionStatus> either = getPropertyModel(resourceId, data); + if (either.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); + return buildErrorResponse(responseFormat); + } + Map properties = either.left().value(); + if (properties == null || properties.size() != 1) { + log.info("Property conetnt is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + Entry entry = properties.entrySet().iterator().next(); + String propertyName = entry.getKey(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + + // create the new property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId); + if (status.isRight()) { + log.info("Failed to create Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + EntryData property = status.left().value(); + String name = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property"); + log.debug("create property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @GET + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}, modifier id is {}", url, userId); + + try { + + // + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId); + + if (status.isRight()) { + log.info("Failed to get Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Entry property = status.left().value(); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, propertyToJson(property)); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); + log.debug("get property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @DELETE + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + try { + + // delete the property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); + if (status.isRight()) { + log.debug("Failed to delete Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Entry property = status.left().value(); + String name = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property"); + log.debug("delete property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + @PUT + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + try { + // convert json to PropertyDefinition + Either, ActionStatus> either = getPropertyModel(resourceId, data); + if (either.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); + return buildErrorResponse(responseFormat); + } + Map properties = either.left().value(); + if (properties == null || properties.size() != 1) { + log.info("Property conetnt is invalid - {}", data); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + Entry entry = properties.entrySet().iterator().next(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + + // update property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId); + if (status.isRight()) { + log.info("Failed to update Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + EntryData property = status.left().value(); + PropertyDefinition propertyDefinition = property.getValue(); + + log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId()); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + return buildOkResponse(responseFormat, propertyToJson(property)); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property"); + log.debug("update property failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + + } + } + + private Either, ActionStatus> getPropertyModel(String resourceId, String data) { + JSONParser parser = new JSONParser(); + JSONObject root; + try { + Map properties = new HashMap(); + root = (JSONObject) parser.parse(data); + + Set entrySet = root.entrySet(); + Iterator iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Entry next = (Entry) iterator.next(); + String propertyName = (String) next.getKey(); + JSONObject value = (JSONObject) next.getValue(); + String jsonString = value.toJSONString(); + Either convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); + if (convertJsonToObject.isRight()) { + return Either.right(convertJsonToObject.right().value()); + } + PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); + propertyDefinition.setUniqueId(uniqueId); + properties.put(propertyName, propertyDefinition); + } + + return Either.left(properties); + } catch (ParseException e) { + log.info("Property conetnt is invalid - {}", data); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } + + private String propertyToJson(Map.Entry property) { + JSONObject root = new JSONObject(); + String propertyName = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); + root.put(propertyName, propertyDefinitionO); + propertyDefinition.getType(); + return root.toString(); + } + + private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { + + Either either = convertObjectToJson(propertyDefinition); + if (either.isRight()) { + return new JSONObject(); + } + String value = either.left().value(); + try { + JSONObject root = (JSONObject) new JSONParser().parse(value); + return root; + } catch (ParseException e) { + log.info("failed to convert input to json"); + log.debug("failed to convert to json", e); + return new JSONObject(); + } + + } + + private Either convertJsonToObject(String data, Class clazz) { + T t = null; + Type constraintType = new TypeToken() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + try { + log.trace("convert json to object. json=\n {}", data); + t = gson.fromJson(data, clazz); + if (t == null) { + log.info("object is null after converting from json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert from json"); + log.debug("failed to convert from json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(t); + } + + private Either convertObjectToJson(PropertyDefinition propertyDefinition) { + Type constraintType = new TypeToken() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); + try { + log.trace("convert object to json. propertyDefinition= {}", propertyDefinition); + String json = gson.toJson(propertyDefinition); + if (json == null) { + log.info("object is null after converting to json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(json); + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert to json"); + log.debug("failed to convert fto json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + + } + + private PropertyBusinessLogic getPropertyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); + return propertytBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java index 98e966e6eb..da42fe2b6f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java @@ -20,14 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.io.IOException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; @@ -36,132 +35,126 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import java.io.IOException; +import com.fasterxml.jackson.databind.SerializationFeature; public class RepresentationUtils { - private static Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName()); - - public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class clazz) { - - JsonObject jsonElement = new JsonObject(); - ArtifactDefinition resourceInfo = null; - - try { - Gson gson = new Gson(); - jsonElement = gson.fromJson(content, jsonElement.getClass()); - String payload = null; - jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD); - //in update the group type is ignored but this spagheti code makes it too complex to remove this field. - jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); - JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); - if (artifactPayload != null && !artifactPayload.isJsonNull()) { - payload = artifactPayload.getAsString(); - } - jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - String json = gson.toJson(jsonElement); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - resourceInfo = mapper.readValue(json, clazz); - resourceInfo.setPayloadData(payload); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); - BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return resourceInfo; - } - - - public static class ResourceRep { - - } - - /** - * Build Representation of given Object - * - * @param elementToRepresent - * @return - * @throws IOException - * @throws JsonGenerationException - * @throws JsonMappingException - */ - public static Object toRepresentation(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException { - - // return theResource; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - return mapper.writeValueAsString(elementToRepresent); - } - - public static T fromRepresentation(String json, Class clazz) { - ObjectMapper mapper = new ObjectMapper(); - T object = null; - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - try { - object = mapper.readValue(json, clazz); - } catch (Exception e) { - log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); - } // return null in case of exception - - return object; - } - - public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class clazz) { - - JsonObject jsonElement = new JsonObject(); - ArtifactDefinition resourceInfo = null; - - try { - Gson gson = new Gson(); - jsonElement = gson.fromJson(content, jsonElement.getClass()); - JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE_FIELD); - if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { - String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); - if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { - StringBuilder sb = new StringBuilder(); - for (String value : ArtifactGroupTypeEnum.getAllTypes()) { - sb.append(value).append(", "); - } - log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb.toString()); - return null; - } else { - jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD); - jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, groupValueUpper); - } - } - String payload = null; - JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); - if (artifactPayload != null && !artifactPayload.isJsonNull()) { - payload = artifactPayload.getAsString(); - } - jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - String json = gson.toJson(jsonElement); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - resourceInfo = mapper.readValue(json, clazz); - resourceInfo.setPayloadData(payload); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update"); - BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); - log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); - } - - return resourceInfo; - } + private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class); + + public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class clazz) { + + JsonObject jsonElement = new JsonObject(); + ArtifactDefinition resourceInfo = null; + + try { + Gson gson = new Gson(); + jsonElement = gson.fromJson(content, jsonElement.getClass()); + String payload = null; + jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE); + //in update the group type is ignored but this spagheti code makes it too complex to remove this field. + jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + resourceInfo = mapper.readValue(json, clazz); + resourceInfo.setPayloadData(payload); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return resourceInfo; + } + + + public static class ResourceRep { + + } + + /** + * Build Representation of given Object + * + * @param elementToRepresent + * @return + * @throws IOException + */ + public static Object toRepresentation(T elementToRepresent) throws IOException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(elementToRepresent); + } + + public static T fromRepresentation(String json, Class clazz) { + ObjectMapper mapper = new ObjectMapper(); + T object = null; + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + try { + object = mapper.readValue(json, clazz); + } catch (Exception e) { + log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); + } // return null in case of exception + + return object; + } + + public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class clazz) { + + JsonObject jsonElement = new JsonObject(); + ArtifactDefinition resourceInfo = null; + + try { + Gson gson = new Gson(); + jsonElement = gson.fromJson(content, jsonElement.getClass()); + JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE); + if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) { + String groupValueUpper = artifactGroupValue.getAsString().toUpperCase(); + if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) { + StringBuilder sb = new StringBuilder(); + for (String value : ArtifactGroupTypeEnum.getAllTypes()) { + sb.append(value).append(", "); + } + log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb); + return null; + } else { + jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE); + jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, groupValueUpper); + } + } + String payload = null; + JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); + if (artifactPayload != null && !artifactPayload.isJsonNull()) { + payload = artifactPayload.getAsString(); + } + jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); + String json = gson.toJson(jsonElement); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + resourceInfo = mapper.readValue(json, clazz); + resourceInfo.setPayloadData(payload); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update"); + log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e); + } + + return resourceInfo; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java index fb4aba6af7..e8769cca9b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java @@ -20,66 +20,56 @@ package org.openecomp.sdc.be.servlets; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonSyntaxException; import com.jcabi.aspects.Loggable; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) public class RequirementsServlet extends BeGenericServlet { - private static Logger log = LoggerFactory.getLogger(RequirementsServlet.class.getName()); - - @PUT - @Path("resources/{resourceId}/requirements/{requirementId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + private static final Logger log = LoggerFactory.getLogger(RequirementsServlet.class); - // Convert RequirementDefinition from JSON - // TODO: it's going to be another object, probably. This is placeholder - // for sake of JSON validation - // RequirementDefinition requirementDefinition; - ResponseFormat responseFormat; - try { - // requirementDefinition = gson.fromJson(requirementData, - // RequirementDefinition.class); - // ..... + @PUT + @Path("resources/{resourceId}/requirements/{requirementId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - // TODO pass real entity - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - } catch (JsonSyntaxException e) { - // INVALID JSON - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } catch (Exception e) { - log.debug("Unexpected error: {}", e); - responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - } + // Convert RequirementDefinition from JSON + // TODO: it's going to be another object, probably. This is placeholder + // for sake of JSON validation + // RequirementDefinition requirementDefinition; + ResponseFormat responseFormat; + try { + // TODO pass real entity + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + } catch (Exception e) { + log.debug("Unexpected error: ", e); + responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java index 54ec6e3b15..5d4001eec5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java @@ -20,15 +20,10 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.jcabi.aspects.Loggable; +import fj.data.Either; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -38,116 +33,116 @@ import org.openecomp.sdc.be.info.ArtifactAccessInfo; import org.openecomp.sdc.be.resources.api.IResourceUploader; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/resources/available") public class ResourceArtifactDownloadServlet extends ToscaDaoServlet { - private static Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class.getName()); - - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @GET - @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}") - // @Produces(MediaType.APPLICATION_OCTET_STREAM) - public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - Response response = null; - try { - // get the artifact data - String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); - - IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext()); - if (resouceUploader == null) { - return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); - - } - Either getArtifactStatus = resouceUploader.getArtifact(artifactId); - - DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext()); - if (logic == null) { - return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); - - } - response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId); - - log.info("Finish handle request of {} | result = {}", url, response.getStatus()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact By Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name"); - log.debug("getResourceArtifactByName failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata") - @Produces(MediaType.APPLICATION_JSON) - public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, - @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - Response response = null; - try { - IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext()); - if (resourceDao == null) { - log.error("resource dao cannot be found"); - response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found"); - return response; - } - - String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); - Either getArtifactStatus = resourceDao.getArtifact(artifactId); - - if (getArtifactStatus.isRight()) { - ResourceUploadStatus status = getArtifactStatus.right().value(); - if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) { - response = Response.status(HttpStatus.SC_NOT_FOUND).build(); - log.debug("Could not find artifact for with id: {}", artifactId); - } else { - response = Response.status(HttpStatus.SC_NO_CONTENT).build(); - log.debug("Could not find artifact for with id: {}", artifactId); - } - return response; - } else { - ESArtifactData artifactData = getArtifactStatus.left().value(); - log.debug("found artifact with id: {}", artifactId); - ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData); - String artifactDataJson = gson.toJson(artifactInfo); - response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); - - log.info("Finish handle request of {} | result = {}", url, response.getStatus()); - return response; - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata"); - log.debug("getResourceArtifactMetadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - - } - - @Override - public Logger getLogger() { - return log; - } + private static final Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class); + + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @GET + @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}") + // @Produces(MediaType.APPLICATION_OCTET_STREAM) + public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + Response response = null; + try { + // get the artifact data + String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); + + IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext()); + if (resouceUploader == null) { + return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); + + } + Either getArtifactStatus = resouceUploader.getArtifact(artifactId); + + DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext()); + if (logic == null) { + return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, ""); + + } + response = logic.downloadArtifact(artifactName, getArtifactStatus, artifactId); + + log.info("Finish handle request of {} | result = {}", url, response.getStatus()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name"); + log.debug("getResourceArtifactByName failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @GET + @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata") + @Produces(MediaType.APPLICATION_JSON) + public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, + @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + Response response = null; + try { + IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext()); + if (resourceDao == null) { + log.error("resource dao cannot be found"); + response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found"); + return response; + } + + String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName); + Either getArtifactStatus = resourceDao.getArtifact(artifactId); + + if (getArtifactStatus.isRight()) { + ResourceUploadStatus status = getArtifactStatus.right().value(); + if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) { + response = Response.status(HttpStatus.SC_NOT_FOUND).build(); + log.debug("Could not find artifact for with id: {}", artifactId); + } else { + response = Response.status(HttpStatus.SC_NO_CONTENT).build(); + log.debug("Could not find artifact for with id: {}", artifactId); + } + return response; + } else { + ESArtifactData artifactData = getArtifactStatus.left().value(); + log.debug("found artifact with id: {}", artifactId); + ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData); + String artifactDataJson = gson.toJson(artifactInfo); + response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build(); + + log.info("Finish handle request of {} | result = {}", url, response.getStatus()); + return response; + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata"); + log.debug("getResourceArtifactMetadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + + } + + @Override + public Logger getLogger() { + return log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java index 3cf2a69fb5..2508423d03 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java @@ -20,24 +20,8 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; - -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import io.swagger.annotations.*; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -53,13 +37,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.annotation.Resource; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; /** * Root resource (exposed at "/" path) @@ -70,115 +56,114 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ResourceUploadServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName()); - public static final String NORMATIVE_TYPE_RESOURCE = "multipart"; - public static final String CSAR_TYPE_RESOURCE = "csar"; - public static final String USER_TYPE_RESOURCE = "user-resource"; - public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import"; - - public enum ResourceAuthorityTypeEnum { - NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true); - - private String urlPath; - private boolean isBackEndImport, isUserTypeResource; - - public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) { - ResourceAuthorityTypeEnum found = null; - for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) { - if (curr.getUrlPath().equals(urlPath)) { - found = curr; - break; - } - } - return found; - } - - private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) { - this.urlPath = urlPath; - this.isBackEndImport = isBackEndImport; - this.isUserTypeResource = isUserTypeResource; - } - - public String getUrlPath() { - return urlPath; - } - - public boolean isBackEndImport() { - return isBackEndImport; - } - - public boolean isUserTypeResource() { - return isUserTypeResource; - } - } - - @Resource - private ResourceImportManager resourceImportManager; - - @POST - @Path("/{resourceAuthority}") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response uploadMultipart( - @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + "," - + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority, - @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, - @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - // updateResourse Query Parameter if false checks if already exist - @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) { - - init(request.getSession().getServletContext()); - try { - - Wrapper responseWrapper = new Wrapper<>(); - Wrapper userWrapper = new Wrapper<>(); - Wrapper uploadResourceInfoWrapper = new Wrapper<>(); - Wrapper yamlStringWrapper = new Wrapper<>(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // When we get an errorResponse it will be filled into the - // responseWrapper - validateAuthorityType(responseWrapper, resourceAuthority); - - ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority); - - commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); - - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file); - - // PayLoad Validations - if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ - commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); - - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); - } - - if (responseWrapper.isEmpty()) { - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Upload Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource"); - log.debug("upload resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /********************************************************************************************************************/ - - private void init(ServletContext context) { - init(log); - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); - resourceImportManager.init(context); - } + private static final Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class); + public static final String NORMATIVE_TYPE_RESOURCE = "multipart"; + public static final String CSAR_TYPE_RESOURCE = "csar"; + public static final String USER_TYPE_RESOURCE = "user-resource"; + public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import"; + + public enum ResourceAuthorityTypeEnum { + NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true); + + private String urlPath; + private boolean isBackEndImport, isUserTypeResource; + + public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) { + ResourceAuthorityTypeEnum found = null; + for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) { + if (curr.getUrlPath().equals(urlPath)) { + found = curr; + break; + } + } + return found; + } + + private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) { + this.urlPath = urlPath; + this.isBackEndImport = isBackEndImport; + this.isUserTypeResource = isUserTypeResource; + } + + public String getUrlPath() { + return urlPath; + } + + public boolean isBackEndImport() { + return isBackEndImport; + } + + public boolean isUserTypeResource() { + return isUserTypeResource; + } + } + + @Resource + private ResourceImportManager resourceImportManager; + + @POST + @Path("/{resourceAuthority}") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response uploadMultipart( + @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + "," + + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority, + @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader, + @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + // updateResourse Query Parameter if false checks if already exist + @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) { + + init(request.getSession().getServletContext()); + try { + + Wrapper responseWrapper = new Wrapper<>(); + Wrapper userWrapper = new Wrapper<>(); + Wrapper uploadResourceInfoWrapper = new Wrapper<>(); + Wrapper yamlStringWrapper = new Wrapper<>(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // When we get an errorResponse it will be filled into the + // responseWrapper + validateAuthorityType(responseWrapper, resourceAuthority); + + ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority); + + commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); + + fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file); + + // PayLoad Validations + if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){ + commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); + + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + } + + if (responseWrapper.isEmpty()) { + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource"); + log.debug("upload resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /********************************************************************************************************************/ + + private void init(ServletContext context) { + init(log); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class); + resourceImportManager.init(context); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java index 8aa5093404..db0d4fb537 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java @@ -20,29 +20,9 @@ package org.openecomp.sdc.be.servlets; -import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.http.HttpStatus; import org.json.JSONObject; import org.openecomp.sdc.be.components.impl.CsarValidationUtils; @@ -66,622 +46,586 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Resources Catalog", description = "Resources Servlet") @Singleton public class ResourcesServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ResourcesServlet.class.getName()); - - @POST - @Path("/resources") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - - Wrapper responseWrapper = new Wrapper<>(); - // UI Import - if (isUIImport(data)) { - performUIImport(responseWrapper, data, request, userId, null); - } - // UI Create - else { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either convertResponse = parseToResource(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse resource"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Resource resource = convertResponse.left().value(); - Either actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); - - if (actionResponse.isRight()) { - log.debug("failed to create resource"); - response = buildErrorResponse(actionResponse.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); - } - responseWrapper.setInnerElement(response); - } - - return responseWrapper.getInnerElement(); - - // return response; - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource"); - log.debug("create resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - private boolean isUIImport(String data) { - boolean isUIImport; - try { - JSONObject json = new JSONObject(data); - String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME); - isUIImport = payloadName != null && !payloadName.isEmpty(); - } catch (Exception e) { - log.debug("failed to parse json sent from client, json:{}", data, e); - isUIImport = false; - } - return isUIImport; - } - - private void performUIImport(Wrapper responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException { - - Wrapper userWrapper = new Wrapper<>(); - Wrapper uploadResourceInfoWrapper = new Wrapper<>(); - Wrapper yamlStringWrapper = new Wrapper<>(); - String resourceInfoJsonString = data; - - ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI; - - commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); - - if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { - fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null); - - // PayLoad Validations - commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); - } - specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); - - if (responseWrapper.isEmpty()) { - handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); - } - } - - public Either parseToResource(String resourceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); - } - - public Either parseToLightResource(String resourceJson, User user) { - Either ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); - if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow) - ret.left().value().setRequirements(null); - ret.left().value().setCapabilities(null); - } - return ret; - } - - @DELETE - @Path("/resources/{resourceId}") - public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = resourceId.toLowerCase(); - ResourceBusinessLogic businessLogic = getResourceBL(context); - ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete resource"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @DELETE - @Path("/resources/{resourceName}/{version}") - public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete resource"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); - log.debug("delete resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/resources/{resourceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - - Response response = null; - - try { - String resourceIdLower = resourceId.toLowerCase(); - ResourceBusinessLogic businessLogic = getResourceBL(context); - log.trace("get resource with id {}", resourceId); - Either actionResponse = businessLogic.getResource(resourceIdLower, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get resource"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) - public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - Response response = null; - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - Either actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource by name and version"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version"); - log.debug("get resource failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/resources/validate-name/{resourceName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}" , userId); - Response response = null; - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - - if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) { - log.debug("invalid resource type received"); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - return response; - - } - ResourceTypeEnum typeEnum = null; - if (resourceType != null) { - typeEnum = ResourceTypeEnum.valueOf(resourceType); - } - Either, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId); - - if (actionResponse.isRight()) { - log.debug("failed to validate resource name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Resource Name"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name"); - log.debug("validate resource name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/resources/certified/abstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - // TODO: any validations??? - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); - Response response = null; - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all abstract resources"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Abstract Resources"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources"); - log.debug("getCertifiedAbstractResources failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @GET - @Path("/resources/certified/notabstract") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - // TODO: any vlidations??? - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}" , url); - Response response = null; - - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get all non abstract resources"); - return buildErrorResponse(actionResponse.right().value()); - } - Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract Resources"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources"); - log.debug("getCertifiedNotAbstractResources failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - - } - - @PUT - @Path("/resources/{resourceId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") }) - public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ResourceBusinessLogic businessLogic = getResourceBL(context); - String resourceIdLower = resourceId.toLowerCase(); - Either updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); - if (updateInfoResource.isRight()) { - log.debug("failed to parse resource metadata"); - response = buildErrorResponse(updateInfoResource.right().value()); - return response; - } - Either actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); - - if (actionResponse.isRight()) { - log.debug("failed to update resource metadata"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata"); - log.debug("Update Resource Metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/resources/{resourceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource already exist") }) - public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @PathParam(value = "resourceId") String resourceId) { - - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - - Wrapper responseWrapper = new Wrapper<>(); - // UI Import - if (isUIImport(data)) { - performUIImport(responseWrapper, data, request, userId, resourceId); - } else { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either convertResponse = parseToLightResource(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse resource"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Resource resource = convertResponse.left().value(); - Either actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId); - - if (actionResponse.isRight()) { - log.debug("failed to update resource"); - response = buildErrorResponse(actionResponse.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); - } - responseWrapper.setInnerElement(response); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource"); - log.debug("update resource failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* - * @GET - * - * @Path("/resources/latestversion/notabstract") - * - * @Consumes(MediaType.APPLICATION_JSON) - * - * @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionNotAbstractResources(@Context final HttpServletRequest request) { //TODO: any vlidations??? ServletContext context = request.getSession().getServletContext(); - * - * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null; - * - * try { - * - * ResourceBusinessLogic businessLogic = getResourceBL(context); - * - * Either, ResponseFormat> actionResponse = businessLogic.getLatestVersionResources(false, HighestFilterEnum.HIGHEST_ONLY); - * - * - * if (actionResponse.isRight()){ log.debug( "failed to get all non abstract resources"); return buildErrorResponse(actionResponse.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - * actionResponse.left().value()); - * - * } catch (Exception e){ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Get Certified Non Abstract Resources"); log.debug("getCertifiedNotAbstractResources failed with exception", e); response = - * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response; - * - * } } - */ - public static List convertMapToList(Map properties) { - if (properties == null) { - return null; - } - - List definitions = new ArrayList<>(); - for (Entry entry : properties.entrySet()) { - String name = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - propertyDefinition.setName(name); - definitions.add(propertyDefinition); - } - - return definitions; - } - - @GET - @Path("/resources/csar/{csaruuid}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) { - - init(log); - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}" , url); - - // retrieve user details - userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); - User user = new User(); - user.setUserId(userId); - - log.debug("user id is {}", userId); - - Response response = null; - - try { - - ResourceBusinessLogic businessLogic = getResourceBL(context); - - Either eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user); - - // validate response - if (eitherResource.isRight()) { - log.debug("failed to get resource from csarUuid : {}", csarUUID); - // response = - // buildErrorResponse(eitherResource.right().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value()); - } else { - Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); - } - - return response; - - } catch (Exception e) { - log.debug("get resource by csar failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } + private static final Logger log = LoggerFactory.getLogger(ResourcesServlet.class); + + @POST + @Path("/resources") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + + Wrapper responseWrapper = new Wrapper<>(); + // UI Import + if (isUIImport(data)) { + performUIImport(responseWrapper, data, request, userId, null); + } + // UI Create + else { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either convertResponse = parseToResource(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse resource"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Resource resource = convertResponse.left().value(); + Either actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null); + + if (actionResponse.isRight()) { + log.debug("failed to create resource"); + response = buildErrorResponse(actionResponse.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation); + } + responseWrapper.setInnerElement(response); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource"); + log.debug("create resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + private boolean isUIImport(String data) { + boolean isUIImport; + try { + JSONObject json = new JSONObject(data); + String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME); + isUIImport = payloadName != null && !payloadName.isEmpty(); + } catch (Exception e) { + log.debug("failed to parse json sent from client, json:{}", data, e); + isUIImport = false; + } + return isUIImport; + } + + private void performUIImport(Wrapper responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException { + + Wrapper userWrapper = new Wrapper<>(); + Wrapper uploadResourceInfoWrapper = new Wrapper<>(); + Wrapper yamlStringWrapper = new Wrapper<>(); + String resourceInfoJsonString = data; + + ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI; + + commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString); + + if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) { + fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null); + + // PayLoad Validations + commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement()); + } + specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum); + + if (responseWrapper.isEmpty()) { + handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId); + } + } + + public Either parseToResource(String resourceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE); + } + + public Either parseToLightResource(String resourceJson, User user) { + Either ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow) + ret.left().value().setRequirements(null); + ret.left().value().setCapabilities(null); + } + return ret; + } + + @DELETE + @Path("/resources/{resourceId}") + public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + String resourceIdLower = resourceId.toLowerCase(); + ResourceBusinessLogic businessLogic = getResourceBL(context); + ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete resource"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @DELETE + @Path("/resources/{resourceName}/{version}") + public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete resource"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource"); + log.debug("delete resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/resources/{resourceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + + Response response = null; + + try { + String resourceIdLower = resourceId.toLowerCase(); + ResourceBusinessLogic businessLogic = getResourceBL(context); + log.trace("get resource with id {}", resourceId); + Either actionResponse = businessLogic.getResource(resourceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get resource"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") }) + public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + Response response = null; + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + Either actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId); + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version"); + log.debug("get resource failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/resources/validate-name/{resourceName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}" , userId); + Response response = null; + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + + if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) { + log.debug("invalid resource type received"); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + return response; + + } + ResourceTypeEnum typeEnum = null; + if (resourceType != null) { + typeEnum = ResourceTypeEnum.valueOf(resourceType); + } + Either, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId); + + if (actionResponse.isRight()) { + log.debug("failed to validate resource name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name"); + log.debug("validate resource name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/resources/certified/abstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + // TODO: any validations??? + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}" , url); + Response response = null; + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all abstract resources"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources"); + log.debug("getCertifiedAbstractResources failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Path("/resources/certified/notabstract") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + // TODO: any vlidations??? + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}" , url); + Response response = null; + + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get all non abstract resources"); + return buildErrorResponse(actionResponse.right().value()); + } + Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources"); + log.debug("getCertifiedNotAbstractResources failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + + } + + @PUT + @Path("/resources/{resourceId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") }) + public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ResourceBusinessLogic businessLogic = getResourceBL(context); + String resourceIdLower = resourceId.toLowerCase(); + Either updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE); + if (updateInfoResource.isRight()) { + log.debug("failed to parse resource metadata"); + response = buildErrorResponse(updateInfoResource.right().value()); + return response; + } + Either actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false); + + if (actionResponse.isRight()) { + log.debug("failed to update resource metadata"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata"); + log.debug("Update Resource Metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/resources/{resourceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource already exist") }) + public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, + @PathParam(value = "resourceId") String resourceId) { + + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + + Wrapper responseWrapper = new Wrapper<>(); + // UI Import + if (isUIImport(data)) { + performUIImport(responseWrapper, data, request, userId, resourceId); + } else { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either convertResponse = parseToLightResource(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse resource"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Resource resource = convertResponse.left().value(); + Either actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId); + + if (actionResponse.isRight()) { + log.debug("failed to update resource"); + response = buildErrorResponse(actionResponse.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); + } + responseWrapper.setInnerElement(response); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource"); + log.debug("update resource failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + public static List convertMapToList(Map properties) { + if (properties == null) { + return null; + } + + List definitions = new ArrayList<>(); + for (Entry entry : properties.entrySet()) { + String name = entry.getKey(); + PropertyDefinition propertyDefinition = entry.getValue(); + propertyDefinition.setName(name); + definitions.add(propertyDefinition); + } + + return definitions; + } + + @GET + @Path("/resources/csar/{csaruuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) { + + init(log); + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}" , url); + + // retrieve user details + userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER); + User user = new User(); + user.setUserId(userId); + + log.debug("user id is {}", userId); + + Response response = null; + + try { + + ResourceBusinessLogic businessLogic = getResourceBL(context); + + Either eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user); + + // validate response + if (eitherResource.isRight()) { + log.debug("failed to get resource from csarUuid : {}", csarUUID); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value()); + } else { + Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation); + } + + return response; + + } catch (Exception e) { + log.debug("get resource by csar failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java new file mode 100644 index 0000000000..f794e8c90b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java @@ -0,0 +1,243 @@ +package org.openecomp.sdc.be.servlets; + +import com.google.common.collect.Sets; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import java.util.Collections; +import java.util.Set; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog/services/{serviceId}/paths") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +@Api(value = "Service Forwarding Path", description = "Service Forwarding Path Servlet") +@Singleton +public class ServiceForwardingPathServlet extends AbstractValidationsServlet { + + private static final Logger log = LoggerFactory.getLogger(ServiceForwardingPathServlet.class); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @ApiOperation(value = "Create Forwarding Path", httpMethod = "POST", notes = "Create Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Create Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response createForwardingPath( + @ApiParam(value = "Forwarding Path to create", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, serviceId, request, userId, false); + } + + + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @ApiOperation(value = "Update Forwarding Path", httpMethod = "PUT", notes = "Update Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Update Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response updateForwardingPath( + @ApiParam(value = "Update Path to create", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + return createOrUpdate(data, serviceId, request, userId, true); + } + + private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + Service updatedService = convertResponse.left().value(); + Either actionResponse ; + if (isUpdate) { + actionResponse = businessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true); + } else { + actionResponse = businessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true); + } + + if (actionResponse.isRight()) { + log.debug("failed to update or create paths"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update"); + log.debug("create or update forwarding path with an error", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/{forwardingPathId}") + @ApiOperation(value = "Get Forwarding Path", httpMethod = "GET", notes = "GET Forwarding Path", response = ForwardingPathDataDefinition.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Get Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response getForwardingPath( + @ApiParam(value = "Forwarding Path to create", required = true) String datax, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either serviceResponse = businessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + if (serviceResponse.isRight()) { + return buildErrorResponse(serviceResponse.right().value()); + } + + UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value(); + + ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition(); + if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) { + forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition)); + + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); + log.debug("update service metadata failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/{forwardingPathId}") + @ApiOperation(value = "Delete Forwarding Path", httpMethod = "DELETE", notes = "Delete Forwarding Path", response = Service.class) + @ApiResponses(value = + {@ApiResponse(code = 201, message = "Delete Forwarding Path"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Forwarding Path already exist")}) + public Response deleteForwardingPath( + @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either, ResponseFormat> actionResponse = businessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true); + + if (actionResponse.isRight()) { + log.debug("failed to delete paths"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Set deletedPaths = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(deletedPaths); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths"); + log.debug("Delete service paths with an error", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + + private Either parseToService(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java index cb90d89ed9..49a1a82e59 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java @@ -20,47 +20,19 @@ package org.openecomp.sdc.be.servlets; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Type; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.reflect.TypeToken; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.*; import org.apache.http.HttpStatus; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.ServiceRelations; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.GroupInstanceProperty; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; @@ -68,15 +40,17 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -84,692 +58,629 @@ import io.swagger.annotations.ApiResponses; @Singleton public class ServiceServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(ServiceServlet.class.getName()); - - @POST - @Path("/services") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Service already exist") }) - public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either convertResponse = parseToService(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse service"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - - Service service = convertResponse.left().value(); - Either actionResponse = businessLogic.createService(service, modifier); - - if (actionResponse.isRight()) { - log.debug("Failed to create service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service"); - log.debug("create service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - public Either parseToService(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - - @GET - @Path("/services/validate-name/{serviceName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - - Either, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId); - - if (actionResponse.isRight()) { - log.debug("failed to get validate service name"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); - log.debug("validate service name failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/audit-records/{componentType}/{componentUniqueId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) - public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - init(log); - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - Wrapper responseWrapper = new Wrapper(); - Wrapper uuidWrapper = new Wrapper<>(); - Wrapper versionWrapper = new Wrapper<>(); - Wrapper userWrapper = new Wrapper<>(); - Wrapper componentWrapper = new Wrapper(); - try { - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - validateComponentType(responseWrapper, componentWrapper, componentType); - } - - if (responseWrapper.isEmpty()) { - fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context); - } - - if (responseWrapper.isEmpty()) { - Either>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); - - if (eitherServiceAudit.isRight()) { - Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value()); - responseWrapper.setInnerElement(errorResponse); - } else { - List> auditRecords = eitherServiceAudit.left().value(); - Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords); - responseWrapper.setInnerElement(okResponse); - - } - } - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); - log.debug("get Service Audit Records failed with exception", e); - Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(errorResponse); - } - return responseWrapper.getInnerElement(); - } - - private void fillUUIDAndVersion(Wrapper responseWrapper, Wrapper uuidWrapper, Wrapper versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) { - - if (componentTypeEnum == ComponentTypeEnum.RESOURCE) { - Either eitherResource = getResourceBL(context).getResource(componentUniqueId, user); - if (eitherResource.isLeft()) { - uuidWrapper.setInnerElement(eitherResource.left().value().getUUID()); - versionWrapper.setInnerElement(eitherResource.left().value().getVersion()); - } else { - responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value())); - } - - } else { - Either eitherService = getServiceBL(context).getService(componentUniqueId, user); - if (eitherService.isLeft()) { - uuidWrapper.setInnerElement(eitherService.left().value().getUUID()); - versionWrapper.setInnerElement(eitherService.left().value().getVersion()); - } else { - responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value())); - - } - } - } - - @DELETE - @Path("/services/{serviceId}") - public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete service"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); - log.debug("delete service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @DELETE - @Path("/services/{serviceName}/{version}") - public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - String userId = request.getHeader(Constants.USER_ID_HEADER); - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier); - - if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { - log.debug("failed to delete service"); - response = buildErrorResponse(actionResponse); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); - log.debug("delete service failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Path("/services/{serviceId}/metadata") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - - Either convertResponse = parseToService(data, modifier); - if (convertResponse.isRight()) { - log.debug("failed to parse service"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - Service updatedService = convertResponse.left().value(); - Either actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to update service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); - log.debug("update service metadata failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - /** - * updates group instance property values - * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated - * @param serviceId - * @param componentInstanceId - * @param groupInstanceId - * @param data - * @param request - * @param userId - * @return - */ - @PUT - @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Response response = null; - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}",userId); - - ServiceBusinessLogic businessLogic; - Either, ResponseFormat> actionResponse = null; - try { - List updatedProperties; - Type listType = new TypeToken>(){}.getType(); - ArrayList newProperties = gson.fromJson(data, listType); - if (newProperties == null) { - actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); - } - if(actionResponse == null){ - log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); - businessLogic = getServiceBL(context); - actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); - if(actionResponse.isRight()){ - actionResponse = Either.right(actionResponse.right().value()); - } - } - if(actionResponse.isLeft()){ - updatedProperties = actionResponse.left().value(); - ObjectMapper mapper = new ObjectMapper(); - String result = mapper.writeValueAsString(updatedProperties); - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } - else{ - response = buildErrorResponse(actionResponse.right().value()); - } - } catch (Exception e) { - log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return response; - } - - @GET - @Path("/services/{serviceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - String serviceIdLower = serviceId.toLowerCase(); - ServiceBusinessLogic businessLogic = getServiceBL(context); - log.debug("get service with id {}", serviceId); - Either actionResponse = businessLogic.getService(serviceIdLower, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to get service"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); - log.debug("get service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @GET - @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) - public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId); - - if (actionResponse.isRight()) { - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version"); - log.debug("get service failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - } - - @POST - @Path("/services/{serviceId}/distribution-state/{state}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId, - @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier); - - if (actionResponse.isRight()) { - log.debug("failed to Update Service Distribution State"); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - Service service = actionResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State"); - log.debug("updateServiceDistributionState failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/distribution/{env}/activate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution") - @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"), - @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request); - - if (distResponse.isRight()) { - log.debug("failed to activate service distribution"); - response = buildErrorResponse(distResponse.right().value()); - return response; - } - Service service = distResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); - log.debug("activate distribution failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/distribution/{did}/markDeployed") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Either distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier); - - if (distResponse.isRight()) { - log.debug("failed to mark distribution as deployed"); - response = buildErrorResponse(distResponse.right().value()); - return response; - } - Service service = distResponse.left().value(); - Object result = RepresentationUtils.toRepresentation(service); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed"); - log.debug("mark distribution as deployed failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @POST - @Path("/services/{serviceId}/tempUrlToBeDeleted") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) - public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Response response = null; - try { - ServiceBusinessLogic businessLogic = getServiceBL(context); - Service service = (businessLogic.getService(serviceId, modifier)).left().value(); - Either res = (businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED)); - - if (res.isRight()) { - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted"); - log.debug("failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } - } - - @GET - @Path("/services/toscatoheat/{artifactName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 404, message = "Artifact not found") }) - public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) { - Response response = null; - - try { - log.debug("artifact name = {}", artifactName); - - Either executeCommand = executeCommand(artifactName); - - if (executeCommand.isRight()) { - log.debug("Failed to convert tosca {} to heat", artifactName); - ResponseFormat responseFormat = executeCommand.right().value(); - response = buildErrorResponse(responseFormat); - } else { - log.debug("Succeed to convert tosca {} to heat", artifactName); - byte[] value = executeCommand.left().value(); - InputStream is = new ByteArrayInputStream(value); - - Map headers = new HashMap<>(); - String heatFileName; - if (artifactName.indexOf(".") > -1) { - heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat"; - } else { - heatFileName = artifactName + ".heat"; - } - headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(heatFileName)); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, is, headers); - } - return response; - - } catch (Exception e) { - log.error("download artifact failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private Either executeCommand(String artifactName) { - - Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); - String toscaFilesDir = configuration.getToscaFilesDir(); - if (toscaFilesDir == null) { - toscaFilesDir = "/apps/jetty/base/be/config/tosca"; - } - String heatTranslator = configuration.getHeatTranslatorPath(); - if (heatTranslator == null) { - heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py"; - } - - log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator); - - StringBuffer output = new StringBuffer(); - - String heatHeader = configuration.getHeatEnvArtifactHeader(); - String heatFooter = configuration.getHeatEnvArtifactFooter(); - - output.append(heatHeader + "\n"); - - MessageFormat mf = new MessageFormat("python {0} --template-file={1}/{2} --template-type=tosca"); - - log.debug("After creating message format"); - - Object[] objArray = { heatTranslator, toscaFilesDir, artifactName }; - String command = null; - try { - command = mf.format(objArray); - } catch (Exception e) { - log.debug("Failed to convert message format", e); - } - - log.debug("Going to run command {}", command); - - Process p; - try { - p = Runtime.getRuntime().exec(command); - int waitFor = p.waitFor(); - log.debug("waitFor = {}", waitFor); - - if (waitFor != 0) { - log.error("Failed runnign the command {}", command); - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName)); - } - - BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); - - String line; - while ((line = reader.readLine()) != null) { - output.append(line + "\n"); - } - - } catch (Exception e) { - log.error("Failed runnign the command {}", command, e); - return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - output.append(heatFooter); - - return Either.left(output.toString().getBytes()); - - } + private static final Logger log = LoggerFactory.getLogger(ServiceServlet.class); + + @POST + @Path("/services") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Service already exist") }) + public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + + Service service = convertResponse.left().value(); + Either actionResponse = businessLogic.createService(service, modifier); + + if (actionResponse.isRight()) { + log.debug("Failed to create service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Object result = RepresentationUtils.toRepresentation(actionResponse.left().value()); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service"); + log.debug("create service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + public Either parseToService(String serviceJson, User user) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + } + + @GET + @Path("/services/validate-name/{serviceName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId); + + if (actionResponse.isRight()) { + log.debug("failed to get validate service name"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); + log.debug("validate service name failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/audit-records/{componentType}/{componentUniqueId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") }) + public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + init(log); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + Wrapper responseWrapper = new Wrapper(); + Wrapper uuidWrapper = new Wrapper<>(); + Wrapper versionWrapper = new Wrapper<>(); + Wrapper userWrapper = new Wrapper<>(); + Wrapper componentWrapper = new Wrapper(); + try { + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + validateComponentType(responseWrapper, componentWrapper, componentType); + } + + if (responseWrapper.isEmpty()) { + fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context); + } + + if (responseWrapper.isEmpty()) { + Either>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId); + + if (eitherServiceAudit.isRight()) { + Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value()); + responseWrapper.setInnerElement(errorResponse); + } else { + List> auditRecords = eitherServiceAudit.left().value(); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords); + responseWrapper.setInnerElement(okResponse); + + } + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name"); + log.debug("get Service Audit Records failed with exception", e); + Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(errorResponse); + } + return responseWrapper.getInnerElement(); + } + + private void fillUUIDAndVersion(Wrapper responseWrapper, Wrapper uuidWrapper, Wrapper versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) { + + if (componentTypeEnum == ComponentTypeEnum.RESOURCE) { + Either eitherResource = getResourceBL(context).getResource(componentUniqueId, user); + if (eitherResource.isLeft()) { + uuidWrapper.setInnerElement(eitherResource.left().value().getUUID()); + versionWrapper.setInnerElement(eitherResource.left().value().getVersion()); + } else { + responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value())); + } + + } else { + Either eitherService = getServiceBL(context).getService(componentUniqueId, user); + if (eitherService.isLeft()) { + uuidWrapper.setInnerElement(eitherService.left().value().getUUID()); + versionWrapper.setInnerElement(eitherService.left().value().getVersion()); + } else { + responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value())); + + } + } + } + + @DELETE + @Path("/services/{serviceId}") + public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete service"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); + log.debug("delete service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @DELETE + @Path("/services/{serviceName}/{version}") + public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + String userId = request.getHeader(Constants.USER_ID_HEADER); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier); + + if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) { + log.debug("failed to delete service"); + response = buildErrorResponse(actionResponse); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service"); + log.debug("delete service failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + @PUT + @Path("/services/{serviceId}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + + Either convertResponse = parseToService(data, modifier); + if (convertResponse.isRight()) { + log.debug("failed to parse service"); + response = buildErrorResponse(convertResponse.right().value()); + return response; + } + Service updatedService = convertResponse.left().value(); + Either actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to update service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata"); + log.debug("update service metadata failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + /** + * updates group instance property values + * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated + * @param serviceId + * @param componentInstanceId + * @param groupInstanceId + * @param data + * @param request + * @param userId + * @return + */ + @PUT + @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Response response = null; + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}",userId); + + ServiceBusinessLogic businessLogic; + Either, ResponseFormat> actionResponse = null; + try { + List updatedProperties; + Type listType = new TypeToken>(){}.getType(); + ArrayList newProperties = gson.fromJson(data, listType); + if (newProperties == null) { + actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); + } + if(actionResponse == null){ + log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId); + businessLogic = getServiceBL(context); + actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties); + if(actionResponse.isRight()){ + actionResponse = Either.right(actionResponse.right().value()); + } + } + if(actionResponse.isLeft()){ + updatedProperties = actionResponse.left().value(); + ObjectMapper mapper = new ObjectMapper(); + String result = mapper.writeValueAsString(updatedProperties); + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } + else{ + response = buildErrorResponse(actionResponse.right().value()); + } + } catch (Exception e) { + log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return response; + } + + @GET + @Path("/services/{serviceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + log.debug("get service with id {}", serviceId); + Either actionResponse = businessLogic.getService(serviceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get service"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); + log.debug("get service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @GET + @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId); + + if (actionResponse.isRight()) { + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version"); + log.debug("get service failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @POST + @Path("/services/{serviceId}/distribution-state/{state}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId, + @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to Update Service Distribution State"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + Service service = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State"); + log.debug("updateServiceDistributionState failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/distribution/{env}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution") + @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"), + @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request); + + if (distResponse.isRight()) { + log.debug("failed to activate service distribution"); + response = buildErrorResponse(distResponse.right().value()); + return response; + } + Service service = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution"); + log.debug("activate distribution failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/distribution/{did}/markDeployed") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Either distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier); + + if (distResponse.isRight()) { + log.debug("failed to mark distribution as deployed"); + response = buildErrorResponse(distResponse.right().value()); + return response; + } + Service service = distResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(service); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed"); + log.debug("mark distribution as deployed failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + @POST + @Path("/services/{serviceId}/tempUrlToBeDeleted") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") }) + public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response; + try { + ServiceBusinessLogic businessLogic = getServiceBL(context); + Service service = (businessLogic.getService(serviceId, modifier)).left().value(); + Either res = businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED); + + if (res.isRight()) { + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted"); + log.debug("failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + + @GET + @Path("/services/{serviceId}/linksMap") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve Service component relations map", httpMethod = "GET", notes = "Returns service components relations", response = ServiceRelations.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") }) + public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + + Response response = null; + try { + String serviceIdLower = serviceId.toLowerCase(); + ServiceBusinessLogic businessLogic = getServiceBL(context); + log.debug("get service components relations with id {}", serviceId); + Either actionResponse = businessLogic.getServiceComponentsRelations(serviceIdLower, modifier); + + if (actionResponse.isRight()) { + log.debug("failed to get service relations data"); + response = buildErrorResponse(actionResponse.right().value()); + return response; + } + + ServiceRelations serviceRelations = actionResponse.left().value(); + Object result = RepresentationUtils.toRepresentation(serviceRelations); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service"); + log.debug("get service relations data failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java new file mode 100644 index 0000000000..fce8dd009e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java @@ -0,0 +1,36 @@ +package org.openecomp.sdc.be.servlets; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Component; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Component +@Provider +public class StorageExceptionMapper implements ExceptionMapper { + + private final ComponentsUtils componentsUtils; + protected Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + public StorageExceptionMapper(ComponentsUtils componentsUtils) { + this.componentsUtils = componentsUtils; + } + + @Override + public Response toResponse(StorageException exception) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(exception.getStorageOperationStatus()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Response.status(responseFormat.getStatus()) + .entity(gson.toJson(responseFormat.getRequestError())) + .build(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java index eea2bfdc42..a30cd3c7b2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.be.servlets; -import javax.servlet.ServletContext; -import javax.ws.rs.core.Response; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; @@ -33,60 +30,45 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.springframework.web.context.WebApplicationContext; +import javax.servlet.ServletContext; +import javax.ws.rs.core.Response; + public abstract class ToscaDaoServlet extends BeGenericServlet { - public abstract Logger getLogger(); - - protected IResourceUploader getResourceUploader(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - - if (webApplicationContextWrapper == null) { - getLogger().error("Failed to get web application context from context."); - return null; - } - - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - - return webApplicationContext.getBean(IResourceUploader.class); - - } - - // protected IToscaYamlBuilder getToscaYamlBuilder(ServletContext context){ - // WebAppContextWrapper webApplicationContextWrapper = - // (WebAppContextWrapper) context - // .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - // - // if (webApplicationContextWrapper == null) { - // getLogger().error("Failed to get web application context from context."); - // return null; - // } - // - // WebApplicationContext webApplicationContext = - // webApplicationContextWrapper - // .getWebAppContext(context); - // - // return webApplicationContext.getBean(IToscaYamlBuilder.class); - // - // } - - protected DownloadArtifactLogic getLogic(ServletContext context) { - DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR); - - if (downloadLogic == null) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInitializationError, "DownloadArtifactLogic from context"); - BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context"); - return null; - } - return downloadLogic; - } - - protected Response buildResponse(int status, String errorMessage) { - - ServletJsonResponse jsonResponse = new ServletJsonResponse(); - jsonResponse.setDescription(errorMessage); - jsonResponse.setSource(Constants.CATALOG_BE); - - Response response = Response.status(status).entity(jsonResponse).build(); - - return response; - } + public abstract Logger getLogger(); + + protected IResourceUploader getResourceUploader(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + + if (webApplicationContextWrapper == null) { + getLogger().error("Failed to get web application context from context."); + return null; + } + + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + + return webApplicationContext.getBean(IResourceUploader.class); + + } + + + protected DownloadArtifactLogic getLogic(ServletContext context) { + DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR); + + if (downloadLogic == null) { + BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context"); + return null; + } + return downloadLogic; + } + + protected Response buildResponse(int status, String errorMessage) { + + ServletJsonResponse jsonResponse = new ServletJsonResponse(); + jsonResponse.setDescription(errorMessage); + jsonResponse.setSource(Constants.CATALOG_BE); + + Response response = Response.status(status).entity(jsonResponse).build(); + + return response; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java index 3ad15961e7..9829566a12 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java @@ -20,20 +20,12 @@ package org.openecomp.sdc.be.servlets; -import java.util.Map; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -48,77 +40,75 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Map; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @Api(value = "Types Fetch Servlet", description = "Types Fetch Servlet") @Singleton public class TypesFetchServlet extends AbstractValidationsServlet { - private static Logger log = LoggerFactory.getLogger(TypesFetchServlet.class.getName()); - - @GET - @Path("dataTypes") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Data types not found") }) - public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - Wrapper responseWrapper = new Wrapper(); - Wrapper userWrapper = new Wrapper(); - ServletContext context = request.getSession().getServletContext(); - - try { - init(log); - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} | modifier id is {}", url, userId); - - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes(); - - if (allDataTypes.isRight()) { - log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value()); - Response errorResponse = buildErrorResponse(allDataTypes.right().value()); - responseWrapper.setInnerElement(errorResponse); - - // return buildErrorResponse(allDataTypes.right().value()); - } else { - - Map dataTypes = allDataTypes.left().value(); - String dataTypeJson = gson.toJson(dataTypes); - Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); - responseWrapper.setInnerElement(okResponse); - - } - } - - return responseWrapper.getInnerElement(); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get all data types"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); - log.debug("get all data types failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - } - } - - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); - return propertytBl; - } + private static final Logger log = LoggerFactory.getLogger(TypesFetchServlet.class); + + @GET + @Path("dataTypes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Data types not found") }) + public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + Wrapper responseWrapper = new Wrapper(); + Wrapper userWrapper = new Wrapper(); + ServletContext context = request.getSession().getServletContext(); + + try { + init(log); + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} | modifier id is {}", url, userId); + + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes(); + + if (allDataTypes.isRight()) { + log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value()); + Response errorResponse = buildErrorResponse(allDataTypes.right().value()); + responseWrapper.setInnerElement(errorResponse); + + } else { + + Map dataTypes = allDataTypes.left().value(); + String dataTypeJson = gson.toJson(dataTypes); + Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson); + responseWrapper.setInnerElement(okResponse); + + } + } + + return responseWrapper.getInnerElement(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); + log.debug("get all data types failed with exception", e); + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + return buildErrorResponse(responseFormat); + } + } + + private PropertyBusinessLogic getPropertyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); + return propertytBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java index bb0be372bf..92f15c4a1d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java @@ -20,27 +20,13 @@ package org.openecomp.sdc.be.servlets; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import javax.annotation.Resource; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.jersey.media.multipart.FormDataParam; import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; @@ -52,7 +38,6 @@ import org.openecomp.sdc.be.components.impl.PolicyTypeImportManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PolicyTypeDefinition; @@ -63,244 +48,256 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.context.WebApplicationContext; - -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; +import org.springframework.stereotype.Controller; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog/uploadType") -@Api(value = "Catalog Types Upload", description = "Upload Type from yaml") -@Singleton +@Api(value = "Catalog Types Upload") +@Controller public class TypesUploadServlet extends AbstractValidationsServlet { - @Resource - private CapabilityTypeImportManager capabilityTypeImportManager; - - @Resource - private InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager; - - @Resource - private CategoriesImportManager categoriesImportManager; - - @Resource - private DataTypeImportManager dataTypeImportManager; - - @Resource - private GroupTypeImportManager groupTypeImportManager; - - @Resource - private PolicyTypeImportManager policyTypeImportManager; - - private static Logger log = LoggerFactory.getLogger(TypesUploadServlet.class.getName()); - - @POST - @Path("/capability") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Capability Type already exist") }) - public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - capabilityTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CapabilityTypeImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name()); - } - - @POST - @Path("/interfaceLifecycle") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) - public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - interfaceLifecycleTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> InterfaceLifecycleTypeImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types"); - } - - @POST - @Path("/categories") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Category already exist") }) - public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - categoriesImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CategoriesImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload)); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories"); - } - - @POST - @Path("/datatypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Data types already exist") }) - public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - dataTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> DataTypeImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); - } - - @POST - @Path("/grouptypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "group types already exist") }) - public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - groupTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> GroupTypeImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName()); - } - - @POST - @Path("/policytypes") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "policy types already exist") }) - public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { - policyTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> PolicyTypeImportManager.class); - ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createPolicyTypes(responseWrapper, ymlPayload); - return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.PolicyType.getName()); - } - - private Response uploadElementTypeServletLogic(ConsumerTwoParam, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { - init(log); - String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); - try { - Wrapper responseWrapper = new Wrapper<>(); - Wrapper userWrapper = new Wrapper<>(); - Wrapper yamlStringWrapper = new Wrapper<>(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - validateUserExist(responseWrapper, userWrapper, userId); - - if (responseWrapper.isEmpty()) { - validateUserRole(responseWrapper, userWrapper.getInnerElement()); - } - - if (responseWrapper.isEmpty()) { - validateDataNotNull(responseWrapper, file); - } - - if (responseWrapper.isEmpty()) { - fillZipContents(yamlStringWrapper, file); - } - - if (responseWrapper.isEmpty()) { - createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement()); - } - - return responseWrapper.getInnerElement(); - - } catch (Exception e) { - log.debug("create {} failed with exception:", elementTypeName, e); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - private void createElementsType(Wrapper responseWrapper, Supplier> elementsCreater) { - Either eitherResult = elementsCreater.get(); - if (eitherResult.isRight()) { - Response response = buildErrorResponse(eitherResult.right().value()); - responseWrapper.setInnerElement(response); - } else { - try { - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); - responseWrapper.setInnerElement(response); - } catch (Exception e) { - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(response); - } - } - } - - // data types - private void createDataTypes(Wrapper responseWrapper, String dataTypesYml) { - final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name()); - } - - // group types - private void createGroupTypes(Wrapper responseWrapper, String groupTypesYml) { - final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); - } - - // policy types - private void createPolicyTypes(Wrapper responseWrapper, String policyTypesYml) { - final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml); - buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); - } - - // data types - private void buildStatusForElementTypeCreate(Wrapper responseWrapper, Supplier>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) { - Either>, ResponseFormat> eitherResult = generateElementTypeFromYml.get(); - - if (eitherResult.isRight()) { - Response response = buildErrorResponse(eitherResult.right().value()); - responseWrapper.setInnerElement(response); - } else { - Object representation; - try { - List> list = eitherResult.left().value(); - ActionStatus status = ActionStatus.OK; - if (list != null) { - - // Group result by the right value - true or false. - // I.e., get the number of data types which are new and - // which are old. - Map>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair::getRight)); - if (collect != null) { - Set keySet = collect.keySet(); - if (keySet.size() == 1) { - Boolean isNew = keySet.iterator().next(); - if (isNew.booleanValue() == true) { - // all data types created at the first time - status = ActionStatus.CREATED; - } else { - // All data types already exists - - status = alreadyExistStatus; - } - } - } - } - representation = RepresentationUtils.toRepresentation(eitherResult.left().value()); - - Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation); - responseWrapper.setInnerElement(response); - - } catch (IOException e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); - log.debug("failed to convert {} to json", elementTypeName, e); - Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - responseWrapper.setInnerElement(response); - } - } - } - - private T initElementTypeImportManager(ServletContext context, Supplier> classGetter) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - T elementTypeImortManager = webApplicationContext.getBean(classGetter.get()); - return elementTypeImortManager; - } + private static final Logger log = LoggerFactory.getLogger(TypesUploadServlet.class); + private CapabilityTypeImportManager capabilityTypeImportManager; + + private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager; + + private final CategoriesImportManager categoriesImportManager; + + private final DataTypeImportManager dataTypeImportManager; + + private final GroupTypeImportManager groupTypeImportManager; + + private final PolicyTypeImportManager policyTypeImportManager; + + public TypesUploadServlet(CapabilityTypeImportManager capabilityTypeImportManager, InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager, CategoriesImportManager categoriesImportManager, DataTypeImportManager dataTypeImportManager, GroupTypeImportManager groupTypeImportManager, PolicyTypeImportManager policyTypeImportManager) { + this.capabilityTypeImportManager = capabilityTypeImportManager; + this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager; + this.categoriesImportManager = categoriesImportManager; + this.dataTypeImportManager = dataTypeImportManager; + this.groupTypeImportManager = groupTypeImportManager; + this.policyTypeImportManager = policyTypeImportManager; + } + + @POST + @Path("/capability") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Capability Type already exist") }) + public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name()); + } + + @POST + @Path("/interfaceLifecycle") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") }) + public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types"); + } + + @POST + @Path("/categories") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Category already exist") }) + public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload)); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories"); + } + + @POST + @Path("/datatypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Data types already exist") }) + public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName()); + } + + @POST + @Path("/grouptypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "group types already exist") }) + public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + ConsumerTwoParam, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload); + return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName()); + } + + @POST + @Path("/policytypes") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "policy types already exist") }) + public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) { + return uploadElementTypeServletLogic(this::createPolicyTypes, file, request, creator, NodeTypeEnum.PolicyType.getName()); + } + + private Response uploadElementTypeServletLogic(ConsumerTwoParam, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) { + init(log); + String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER); + try { + Wrapper responseWrapper = new Wrapper<>(); + Wrapper userWrapper = new Wrapper<>(); + Wrapper yamlStringWrapper = new Wrapper<>(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + validateUserExist(responseWrapper, userWrapper, userId); + + if (responseWrapper.isEmpty()) { + validateUserRole(responseWrapper, userWrapper.getInnerElement()); + } + + if (responseWrapper.isEmpty()) { + validateDataNotNull(responseWrapper, file); + } + + if (responseWrapper.isEmpty()) { + fillZipContents(yamlStringWrapper, file); + } + + if (responseWrapper.isEmpty()) { + createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement()); + } + + return responseWrapper.getInnerElement(); + + } catch (Exception e) { + log.debug("create {} failed with exception:", elementTypeName, e); + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private void createElementsType(Wrapper responseWrapper, Supplier> elementsCreater) { + Either eitherResult = elementsCreater.get(); + if (eitherResult.isRight()) { + Response response = buildErrorResponse(eitherResult.right().value()); + responseWrapper.setInnerElement(response); + } else { + try { + Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value())); + responseWrapper.setInnerElement(response); + } catch (Exception e) { + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(response); + log.error("#createElementsType - json serialization failed with error: ", e); + } + } + } + + // data types + private void createDataTypes(Wrapper responseWrapper, String dataTypesYml) { + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name()); + } + + // group types + private void createGroupTypes(Wrapper responseWrapper, String groupTypesYml) { + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name()); + } + + // policy types + private void createPolicyTypes(Wrapper responseWrapper, String policyTypesYml) { + final Supplier>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml); + buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name()); + } + + // data types + private void buildStatusForElementTypeCreate(Wrapper responseWrapper, Supplier>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) { + Either>, ResponseFormat> eitherResult = generateElementTypeFromYml.get(); + + if (eitherResult.isRight()) { + Response response = buildErrorResponse(eitherResult.right().value()); + responseWrapper.setInnerElement(response); + } else { + Object representation; + try { + List> list = eitherResult.left().value(); + ActionStatus status = ActionStatus.OK; + if (list != null) { + + // Group result by the right value - true or false. + // I.e., get the number of data types which are new and + // which are old. + Map>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair::getRight)); + if (collect != null) { + Set keySet = collect.keySet(); + if (keySet.size() == 1) { + Boolean isNew = keySet.iterator().next(); + if (isNew.booleanValue()) { + // all data types created at the first time + status = ActionStatus.CREATED; + } else { + // All data types already exists + + status = alreadyExistStatus; + } + } + } + } + representation = RepresentationUtils.toRepresentation(eitherResult.left().value()); + + Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation); + responseWrapper.setInnerElement(response); + + } catch (IOException e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName); + log.debug("failed to convert {} to json", elementTypeName, e); + Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + responseWrapper.setInnerElement(response); + } + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java index a6f6359ac1..c9ea5dd951 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java @@ -20,10 +20,22 @@ package org.openecomp.sdc.be.servlets; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.List; +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.servlet.ServletContext; @@ -40,437 +52,352 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.jcabi.aspects.Loggable; - -import fj.data.Either; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/user") @Api(value = "User Administration", description = "User admininstarator operations") @Singleton public class UserAdminServlet extends BeGenericServlet { - private static final String ROLE_DELIMITER = ","; - private static Logger log = LoggerFactory.getLogger(UserAdminServlet.class.getName()); - - /*************************************** - * API start - *************************************************************/ - - /* User by userId CRUD start */ - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve all user details - @GET - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either either = userAdminManager.getUser(userId, false); - - if (either.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } else { - if (either.left().value() != null) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); - log.debug("get user failed with unexpected error: {}", e.getMessage(), e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // update user - internal API - /* - * @POST - * - * @Path("/{userId}") - * - * @Consumes(MediaType.APPLICATION_JSON) - * - * @Produces(MediaType.APPLICATION_JSON) - * - * @ApiOperation(value = "update user - internal API", notes = "Update user", response = User.class) - * - * @ApiResponses(value = { - * - * @ApiResponse(code = 200, message = "Update user OK"), - * - * @ApiResponse(code = 400, message = "Invalid Content."), - * - * @ApiResponse(code = 403, message = "Missing information/Restricted operation"), - * - * @ApiResponse(code = 404, message = "User not found"), - * - * @ApiResponse(code = 405, message = "Method Not Allowed"), - * - * @ApiResponse(code = 409, message = "User already exists"), - * - * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser, - * - * @Context final HttpServletRequest request, - * - * @ApiParam(value="json describe the update user", required=true) String data, - * - * @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { - * - * ServletContext context = request.getSession().getServletContext(); - * - * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url); - * - * // get modifier id User modifier = new User(); modifier.setUserId(modifierAttId); log.debug("modifier id is {}", modifierAttId); - * - * Response response = null; - * - * try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either - * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser); - * - * if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response = - * buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response; - * - * } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Update User Metadata"); log.debug("Update User Metadata failed with exception", e); response = - * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response; - * - * } } - * - */ - /* User userId CRUD end */ - - /* User role CRUD start */ - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // retrieve user role - @GET - @Path("/{userId}/role") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(getRole) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either either = userAdminManager.getUser(userId, false); - if (either.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); - } else { - if (either.left().value() != null) { - String roleJson = ("{ \"role\" : \"" + either.left().value().getRole().toString() + "\" }"); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User Role"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role"); - log.debug("Get user role failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // update user role - @POST - @Path("/{userId}/role") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "update user role", notes = "Update user role", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"), - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request, - @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(modifierUserId); - log.debug("modifier id is {}", modifierUserId); - - Response response = null; - - try { - UserBusinessLogic businessLogic = getUserAdminManager(context); - User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); - Either updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole()); - - if (updateUserResponse.isRight()) { - log.debug("failed to update user role"); - response = buildErrorResponse(updateUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); - log.debug("Update User Role failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* User role CRUD end */ - - /* New user CRUD start */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { - - ServletContext context = request.getSession().getServletContext(); - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - // get modifier id - User modifier = new User(); - modifier.setUserId(modifierAttId); - log.debug("modifier id is {}", modifierAttId); - - Response response = null; - - try { - UserBusinessLogic businessLogic = getUserAdminManager(context); - User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value(); - Either createUserResponse = businessLogic.createUser(modifier, newUserInfo); - - if (createUserResponse.isRight()) { - log.debug("failed to create user"); - response = buildErrorResponse(createUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); - log.debug("Create User failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - /* New user CRUD end */ - - /* User authorization start */ - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // User Authorization - @GET - @Path("/authorize") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - - @ApiOperation(value = "authorize", notes = "authorize user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName, - @HeaderParam("HTTP_CSP_EMAIL") String email) { - - try { - userId = (userId != null ? URLDecoder.decode(userId, "UTF-8") : null); - firstName = (firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null); - lastName = (lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null); - email = (email != null ? URLDecoder.decode(email, "UTF-8") : null); - } catch (UnsupportedEncodingException e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Authorize User - decode headers"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers"); - ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(errorResponseWrapper); - } - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {}", url); - - User authUser = new User(); - authUser.setUserId(userId); - authUser.setFirstName(firstName); - authUser.setLastName(lastName); - authUser.setEmail(email); - log.debug("auth user id is {}", userId); - - Response response = null; - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either authorize = userAdminManager.authorize(authUser); - - if (authorize.isRight()) { - log.debug("authorize user failed"); - response = buildErrorResponse(authorize.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - log.debug("authorize user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - /* User authorization end */ - - @GET - @Path("/admins") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getAdminsUser(@PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext()); - - if (either.isRight()) { - log.debug("Failed to get all admin users"); - return buildErrorResponse(either.right().value()); - } else { - if (either.left().value() != null) { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } else { - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Administrators"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators"); - log.debug("get all admins failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - - @GET - @Path("/users") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"), - @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, - @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userId); - - List rolesList = new ArrayList<>(); - if (roles != null && !roles.trim().isEmpty()) { - String[] rolesArr = roles.split(ROLE_DELIMITER); - for (String role : rolesArr) { - rolesList.add(role.trim()); - } - } - - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles); - - if (either.isRight()) { - log.debug("Failed to get ASDC users"); - return buildErrorResponse(either.right().value()); - } else { - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); - log.debug("get users failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - } - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // delete user - @DELETE - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "delete user", notes = "Delete user", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) { - - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("Start handle request of {} modifier id is {}", url, userIdHeader); - - User modifier = new User(); - modifier.setUserId(userIdHeader); - - Response response = null; - try { - UserBusinessLogic userAdminManager = getUserAdminManager(context); - Either deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId); - - if (deactiveUserResponse.isRight()) { - log.debug("Failed to deactivate user"); - response = buildErrorResponse(deactiveUserResponse.right().value()); - return response; - } - response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value()); - return response; - - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users"); - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); - log.debug("deactivate user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } + private static final String ROLE_DELIMITER = ","; + private static final Logger log = LoggerFactory.getLogger(UserAdminServlet.class); + + /*************************************** + * API start + *************************************************************/ + + /* User by userId CRUD start */ + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // retrieve all user details + @GET + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either either = userAdminManager.getUser(userId, false); + + if (either.isRight()) { + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } else { + if (either.left().value() != null) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); + log.debug("get user failed with unexpected error: {}", e.getMessage(), e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/{userId}/role") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), + @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(getRole) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either either = userAdminManager.getUser(userId, false); + if (either.isRight()) { + return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId)); + } else { + if (either.left().value() != null) { + String roleJson = "{ \"role\" : \"" + either.left().value().getRole() + "\" }"; + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role"); + log.debug("Get user role failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // update user role + @POST + @Path("/{userId}/role") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "update user role", notes = "Update user role", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"), + @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request, + @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(modifierUserId); + log.debug("modifier id is {}", modifierUserId); + + Response response = null; + + try { + UserBusinessLogic businessLogic = getUserAdminManager(context); + User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); + Either updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole()); + + if (updateUserResponse.isRight()) { + log.debug("failed to update user role"); + response = buildErrorResponse(updateUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); + log.debug("Update User Role failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + /* User role CRUD end */ + + /* New user CRUD start */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) { + + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + // get modifier id + User modifier = new User(); + modifier.setUserId(modifierAttId); + log.debug("modifier id is {}", modifierAttId); + + Response response = null; + + try { + UserBusinessLogic businessLogic = getUserAdminManager(context); + User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value(); + Either createUserResponse = businessLogic.createUser(modifier, newUserInfo); + + if (createUserResponse.isRight()) { + log.debug("failed to create user"); + response = buildErrorResponse(createUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata"); + log.debug("Create User failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + + } + } + + /* New user CRUD end */ + + /* User authorization start */ + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // User Authorization + @GET + @Path("/authorize") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + + @ApiOperation(value = "authorize", notes = "authorize user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName, + @HeaderParam("HTTP_CSP_EMAIL") String email) { + + try { + userId = userId != null ? URLDecoder.decode(userId, "UTF-8") : null; + firstName = firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null; + lastName = lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null; + email = email != null ? URLDecoder.decode(email, "UTF-8") : null; + } catch (UnsupportedEncodingException e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers"); + ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); + log.error("#authorize - authorization decoding failed with error: ", e); + return buildErrorResponse(errorResponseWrapper); + } + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {}", url); + + User authUser = new User(); + authUser.setUserId(userId); + authUser.setFirstName(firstName); + authUser.setLastName(lastName); + authUser.setEmail(email); + log.debug("auth user id is {}", userId); + + Response response = null; + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either authorize = userAdminManager.authorize(authUser); + + if (authorize.isRight()) { + log.debug("authorize user failed"); + response = buildErrorResponse(authorize.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value()); + return response; + + } catch (Exception e) { + log.debug("authorize user failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + /* User authorization end */ + + @GET + @Path("/admins") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getAdminsUser(@Context final HttpServletRequest request) { + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + + UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); + + try { + Either, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext()); + + if (either.isRight()) { + log.debug("Failed to get all admin users"); + return buildErrorResponse(either.right().value()); + } else { + if (either.left().value() != null) { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } else { + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators"); + log.debug("get all admins failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @GET + @Path("/users") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"), + @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId, + @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + List rolesList = new ArrayList<>(); + if (roles != null && !roles.trim().isEmpty()) { + String[] rolesArr = roles.split(ROLE_DELIMITER); + for (String role : rolesArr) { + rolesList.add(role.trim()); + } + } + + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles); + + if (either.isRight()) { + log.debug("Failed to get ASDC users"); + return buildErrorResponse(either.right().value()); + } else { + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); + log.debug("get users failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // delete user + @DELETE + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete user", notes = "Delete user", response = User.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"), + @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") }) + public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) { + + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userIdHeader); + + User modifier = new User(); + modifier.setUserId(userIdHeader); + + Response response = null; + try { + UserBusinessLogic userAdminManager = getUserAdminManager(context); + Either deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId); + + if (deactiveUserResponse.isRight()) { + log.debug("Failed to deactivate user"); + response = buildErrorResponse(deactiveUserResponse.right().value()); + return response; + } + response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value()); + return response; + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users"); + log.debug("deactivate user failed with unexpected error: {}", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java index faebb7614b..fb5710cc20 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,19 @@ package org.openecomp.sdc.be.switchover.detector; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.HttpRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; import java.net.InetAddress; import java.util.Properties; import java.util.concurrent.ExecutorService; @@ -29,293 +42,272 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.rest.HttpRestClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - @Component("switchover-detector") public class SwitchoverDetector { - protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector"; + protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector"; - private static Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT); + private static final Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT); - private SwitchoverDetectorConfig switchoverDetectorConfig; + private SwitchoverDetectorConfig switchoverDetectorConfig; - private Properties authHeader = null; + private Properties authHeader = null; - private long detectorInterval = 60; + private long detectorInterval = 60; - private int maxBeQueryAttempts = 3; + private int maxBeQueryAttempts = 3; - private int maxFeQueryAttempts = 3; + private int maxFeQueryAttempts = 3; - private Boolean beMatch = null; + private Boolean beMatch = null; - private Boolean feMatch = null; + private Boolean feMatch = null; - private static Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class); - private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); + private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState(); - private ScheduledFuture scheduledFuture = null; + private ScheduledFuture scheduledFuture = null; - ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Switchover-Detector-Task"); - } - }); + ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "Switchover-Detector-Task"); + } + }); - SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; + SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null; - public enum SwitchoverDetectorState { + public enum SwitchoverDetectorState { - UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby"); + UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby"); - private String state; + private String state; - SwitchoverDetectorState(String state) { - this.state = state; - } + SwitchoverDetectorState(String state) { + this.state = state; + } - public String getState() { - return state; - } - } + public String getState() { + return state; + } + } - public enum SwitchoverDetectorGroup { + public enum SwitchoverDetectorGroup { - BE_SET("beSet"), FE_SET("feSet"); + BE_SET("beSet"), FE_SET("feSet"); - private String group; + private String group; - SwitchoverDetectorGroup(String group) { - this.group = group; - } + SwitchoverDetectorGroup(String group) { + this.group = group; + } - public String getGroup() { - return group; - } - } + public String getGroup() { + return group; + } + } - public String getSiteMode() { - return siteMode; - } + public String getSiteMode() { + return siteMode; + } - public void setSiteMode(String mode) { - this.siteMode = mode; - } + public void setSiteMode(String mode) { + this.siteMode = mode; + } - private Boolean queryBe() { - return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts); - } + private Boolean queryBe() { + return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts); + } - private Boolean queryFe() { - return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts); - } + private Boolean queryFe() { + return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts); + } - private void setAuthorizationProperties() { - String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword(); - String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes())); - authHeader = new Properties(); - authHeader.put("Authorization", auth); - } + private void setAuthorizationProperties() { + String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword(); + String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes())); + authHeader = new Properties(); + authHeader.put("Authorization", auth); + } - private void initializeSiteMode() { - while (siteMode == SwitchoverDetectorState.UNKNOWN.getState()) { + private void initializeSiteMode() { + while (siteMode.equals(SwitchoverDetectorState.UNKNOWN.getState())) { - beMatch = queryBe(); - feMatch = queryFe(); + beMatch = queryBe(); + feMatch = queryFe(); - if (beMatch == feMatch && beMatch != null) { - if (beMatch) { - setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); - } else { - setSiteMode(SwitchoverDetectorState.STANDBY.getState()); - } - } - } - } + if (beMatch == feMatch && beMatch != null) { + if (beMatch) { + setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); + } else { + setSiteMode(SwitchoverDetectorState.STANDBY.getState()); + } + } + } + } - private Boolean queryGss(String fqdn, String vip, int maxAttempts) { + private Boolean queryGss(String fqdn, String vip, int maxAttempts) { - Boolean result = null; - int attempts = 0; + Boolean result = null; + int attempts = 0; - while (result == null && (++attempts < maxAttempts)) { - try { - InetAddress inetAddress = InetAddress.getByName(fqdn); - result = inetAddress.getHostAddress().equals(vip); + while (result == null && (++attempts < maxAttempts)) { + try { + InetAddress inetAddress = InetAddress.getByName(fqdn); + result = inetAddress.getHostAddress().equals(vip); - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - logger.debug("Error occured during switchover detector query, Result is {}", message, e); - } - } - if (null == result) { - BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts"); - } - return result; - } - - public class SwitchoverDetectorScheduledTask implements Runnable { - - public SwitchoverDetectorScheduledTask() { - - } - - @Override - public void run() { - logger.trace("Executing Switchover Detector Task - Start"); - - initializeSiteMode(); - - Boolean beRes = queryBe(); - Boolean feRes = queryFe(); - - if (null == beRes || null == feRes) { - return; - } - - Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) & (beMatch != beRes || feMatch != feRes); - - updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired); - - beMatch = beRes; - feMatch = feRes; - } - - ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "Switchover-Detector-Thread"); - } - }); - - private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) { - if (bothMatch && previousModeStandby) { - logger.trace("Site switch over was done. Site is now in active mode"); - setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); - BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); - } else if (!bothMatch && !previousModeStandby) { - logger.trace("Site switch over was done. Site is now in stand-by mode"); - setSiteMode(SwitchoverDetectorState.STANDBY.getState()); - BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); - } - if (updateRequired) { - changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup()); - changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup()); - publishNetwork(); - } - } - - private void changeSitePriority(String groupToSet) { - - String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl(); - String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody(); - - HttpRestClient httpRestClient = new HttpRestClient(); - - try { - httpRestClient.doPUT(url, authHeader, body); - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - - logger.debug("Error occured during change site priority request, Result is {}", message, e); - } - - } - - private void publishNetwork() { - - String url = switchoverDetectorConfig.getPublishNetworkUrl(); - String body = switchoverDetectorConfig.getPublishNetworkBody(); - - HttpRestClient httpRestClient = new HttpRestClient(); - - try { - httpRestClient.doPOST(url, authHeader, body); - - } catch (Exception e) { - String message = e.getMessage(); - if (message == null) { - message = e.getClass().getName(); - } - - logger.debug("Error occured during publish network request, Result is {}", message, e); - } - } - - } - - @PostConstruct - private void init() { - logger.info("Enter init method of SwitchoverDetector"); - - switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector(); - - if (!switchoverDetectorConfig.getEnabled()) { - logger.info("switchover detector service is disabled"); - return; - } - - Long detectorIntervalConfig = switchoverDetectorConfig.getInterval(); - if (detectorIntervalConfig != null) { - detectorInterval = detectorIntervalConfig.longValue(); - } - - Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); - if (maxAttempts != null) { - maxBeQueryAttempts = maxAttempts.intValue(); - } - maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); - if (maxAttempts != null) { - maxFeQueryAttempts = maxAttempts.intValue(); - } - - setAuthorizationProperties(); - logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval); - - this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask(); - startSwitchoverDetectorTask(); - logger.trace("Exit init method of SwitchoverDetector"); - - } - - @PreDestroy - private void destroy() { - - if (scheduledFuture != null) { - scheduledFuture.cancel(true); - scheduledFuture = null; - } - - if (switchoverDetectorScheduler != null) { - switchoverDetectorScheduler.shutdown(); - } - - } - - public void startSwitchoverDetectorTask() { - if (this.scheduledFuture == null) { - this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS); - } - } + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during switchover detector query, Result is {}", message, e); + } + } + if (null == result) { + BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts"); + } + return result; + } + + public class SwitchoverDetectorScheduledTask implements Runnable { + + public SwitchoverDetectorScheduledTask() { + + } + + @Override + public void run() { + logger.trace("Executing Switchover Detector Task - Start"); + + initializeSiteMode(); + + Boolean beRes = queryBe(); + Boolean feRes = queryFe(); + + if (null == beRes || null == feRes) { + return; + } + + Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) && (beMatch != beRes || feMatch != feRes); + + updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired); + + beMatch = beRes; + feMatch = feRes; + } + + ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r, "Switchover-Detector-Thread"); + } + }); + + private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) { + if (bothMatch && previousModeStandby) { + logger.trace("Site switch over was done. Site is now in active mode"); + setSiteMode(SwitchoverDetectorState.ACTIVE.getState()); + BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); + } else if (!bothMatch && !previousModeStandby) { + logger.trace("Site switch over was done. Site is now in stand-by mode"); + setSiteMode(SwitchoverDetectorState.STANDBY.getState()); + BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode); + } + if (updateRequired) { + changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup()); + changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup()); + publishNetwork(); + } + } + + private void changeSitePriority(String groupToSet) { + + String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl(); + String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody(); + + try { + HttpRequest.put(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON)); + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during change site priority request, Result is {}", message, e); + } + + } + + private void publishNetwork() { + + String url = switchoverDetectorConfig.getPublishNetworkUrl(); + String body = switchoverDetectorConfig.getPublishNetworkBody(); + try { + HttpRequest.post(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON)); + } catch (Exception e) { + String message = e.getMessage(); + if (message == null) { + message = e.getClass().getName(); + } + logger.debug("Error occured during publish network request, Result is {}", message, e); + } + } + + } + + @PostConstruct + private void init() { + logger.info("Enter init method of SwitchoverDetector"); + + switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector(); + + if (!switchoverDetectorConfig.getEnabled()) { + logger.info("switchover detector service is disabled"); + return; + } + + Long detectorIntervalConfig = switchoverDetectorConfig.getInterval(); + if (detectorIntervalConfig != null) { + detectorInterval = detectorIntervalConfig.longValue(); + } + + Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts(); + if (maxAttempts != null) { + maxBeQueryAttempts = maxAttempts.intValue(); + } + maxAttempts = switchoverDetectorConfig.getFeResolveAttempts(); + if (maxAttempts != null) { + maxFeQueryAttempts = maxAttempts.intValue(); + } + + setAuthorizationProperties(); + logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval); + + this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask(); + startSwitchoverDetectorTask(); + logger.trace("Exit init method of SwitchoverDetector"); + + } + + @PreDestroy + private void destroy() { + + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; + } + + if (switchoverDetectorScheduler != null) { + switchoverDetectorScheduler.shutdown(); + } + + } + + public void startSwitchoverDetectorTask() { + if (this.scheduledFuture == null) { + this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java index 13356e5de4..f13331ed0b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java @@ -20,19 +20,19 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.openecomp.sdc.generator.data.ArtifactType; +import java.util.List; + public class ArtifactTypes { - private List artifactTypes; + private List artifactTypes; - public List getArtifactTypes() { - return artifactTypes; - } + public List getArtifactTypes() { + return artifactTypes; + } - public void setArtifactTypes(List artifactTypes) { - this.artifactTypes = artifactTypes; - } + public void setArtifactTypes(List artifactTypes) { + this.artifactTypes = artifactTypes; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java deleted file mode 100644 index 7fecced358..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.tosca; - -import org.openecomp.sdc.be.model.Component; - -public class CSARTool { - public static byte[] createCsar(Component component) { - - final String TOSCA_META_VERSION = "1.0"; - final String CSAR_VERSION = component.getCsarVersion(); - final String CREATED_BY = component.getCreatorFullName(); - final String ENTRY_DEFINITIONS = component.getNormalizedName(); - - /* - * StringBuilder builder = new StringBuilder(); try( FileOutputStream f = new FileOutputStream("test.zip"); ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); ){ } - */ - - return null; - } - - public static String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s"; - - return null; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java index 886b654b81..4dbbf925d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java @@ -20,50 +20,34 @@ package org.openecomp.sdc.be.tosca; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.tosca.ToscaUtils.SubstituitionEntry; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; +import org.openecomp.sdc.be.tosca.model.*; import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.*; -import fj.data.Either; /** * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template * @@ -71,502 +55,545 @@ import fj.data.Either; @org.springframework.stereotype.Component("capabilty-requirement-convertor") @Scope(value = "singleton") public class CapabiltyRequirementConvertor { - - private static final String NO_CAPABILITIES = "No Capabilities for node type"; - private static CapabiltyRequirementConvertor instance; - private static Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class.getName()); - public static final String PATH_DELIMITER = "."; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - - protected CapabiltyRequirementConvertor() {} - - public static synchronized CapabiltyRequirementConvertor getInstance() { - if (instance == null) { - instance = new CapabiltyRequirementConvertor(); - } - return instance; - } - /** - * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template - * @param componentInstance - * @param dataTypes - * @param nodeTemplate - * @return - */ - public Either convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map dataTypes, ToscaNodeTemplate nodeTemplate) { - - Map> capabilitiesInst = componentInstance.getCapabilities(); - if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { - Map capabilties = new HashMap<>(); - capabilitiesInst.entrySet().forEach(e -> { - List capList = e.getValue(); - if (capList != null && !capList.isEmpty()) { - capList.forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilties, c)); - } - }); - if (MapUtils.isNotEmpty(capabilties)) { - nodeTemplate.setCapabilities(capabilties); - } - } - return Either.left(nodeTemplate); - } - - private void convertOverridenProperties(ComponentInstance componentInstance, Map dataTypes, Map capabilties, CapabilityDefinition c) { - if (CollectionUtils.isNotEmpty(c.getProperties())) { - c.getProperties() - .stream() - .filter(p -> p.getValue() != null || p.getDefaultValue() != null) - .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties, c, p)); - } - } - - private void convertOverridenProperty(ComponentInstance componentInstance, Map dataTypes, Map capabilties, CapabilityDefinition c, ComponentInstanceProperty p) { - if (logger.isDebugEnabled()) { - logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), c.getName(), p.getValue()); - } - ToscaTemplateCapability toscaTemplateCapability = capabilties.get(c.getName()); - if (toscaTemplateCapability == null) { - toscaTemplateCapability = new ToscaTemplateCapability(); - capabilties.put(c.getName(), toscaTemplateCapability); - } - Map toscaCapProp = toscaTemplateCapability.getProperties(); - if (toscaCapProp == null) { - toscaCapProp = new HashMap<>(); - } - Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); - toscaCapProp.put(p.getName(), convertedValue); - toscaTemplateCapability.setProperties(toscaCapProp); - } - - private Object convertInstanceProperty(Map dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { - logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); - String propertyType = prop.getType(); - String innerType = null; - if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { - innerType = prop.getSchema().getProperty().getType(); - } - String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); - return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); - } - /** - * Allows to convert requirements of a node type to tosca template requirements representation - * @param component - * @param nodeType - * @return - */ - public Either convertRequirements(Component component, ToscaNodeType nodeType) { - List> toscaRequirements = convertRequirementsAsList(component); - if (!toscaRequirements.isEmpty()) { - nodeType.setRequirements(toscaRequirements); - } - logger.debug("Finish convert Requirements for node type"); - - return Either.left(nodeType); - } - - /** - * Allows to convert component requirements to the tosca template substitution mappings requirements - * @param componentsCache - * @param component - * @param substitutionMappings - * @return - */ - public Either convertSubstitutionMappingRequirements(Map componentsCache, Component component, SubstitutionMapping substitutionMappings) { - Either result = Either.left(substitutionMappings); - Either, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); - if(toscaRequirementsRes.isRight()){ - result = Either.right(toscaRequirementsRes.right().value()); - logger.error("Failed convert requirements for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { - substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); - result = Either.left(substitutionMappings); - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - return result; - } - - private List> convertRequirementsAsList(Component component) { - Map> requirements = component.getRequirements(); - List> toscaRequirements = new ArrayList<>(); - if (requirements != null) { - for (Map.Entry> entry : requirements.entrySet()) { - entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { - ImmutablePair pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); - Map requirement = new HashMap<>(); - - requirement.put(pair.left, pair.right); - toscaRequirements.add(requirement); - }); - logger.debug("Finish convert Requirements for node type"); - } - } else { - logger.debug("No Requirements for node type"); - } - return toscaRequirements; - } - - private boolean filter(Component component, String ownerId) { - return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); - } - - private boolean isNodeTypeOwner(Component component, String ownerId) { - return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); - } - - private String getSubPathByLastDelimiterAppearance(String path) { - return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); - } - - private Either, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map componentsCache, Component component) { - Map> requirements = component.getRequirements(); - Either, ToscaError> result; - if (requirements != null) { - result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); - } else { - result = Either.left(Maps.newHashMap()); - logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); - } - return result; - } - - private Either, ToscaError> buildAddSubstitutionMappingsRequirements(Map componentsCache, Component component, Map> requirements) { - - Map toscaRequirements = new HashMap<>(); - Either, ToscaError> result = null; - for (Map.Entry> entry : requirements.entrySet()) { - Optional failedToAddRequirement = entry.getValue() - .stream() - .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private Either, ToscaError> buildAddSubstitutionMappingsCapabilities(Map componentsCache, Component component, Map> capabilities) { - - Map toscaRequirements = new HashMap<>(); - Either, ToscaError> result = null; - for (Map.Entry> entry : capabilities.entrySet()) { - Optional failedToAddRequirement = entry.getValue() - .stream() - .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); - } - logger.debug("Finish convert capalilities for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private boolean addEntry(Map componentsCache, Map capReqMap, Component component, String name, String parentName, List path){ - - SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); - - if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, entry)){ - return false; - } - logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); - if (entry.getSourceName() != null) { - addEntry(capReqMap, component, path, entry); - } - logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); - return true; - - } - - private boolean shouldBuildSubstitutionName(Component component, List path) { - return !ToscaUtils.isComplexVfc(component) && CollectionUtils.isNotEmpty(path) && path.iterator().hasNext(); - } - - private boolean buildSubstitutedNamePerInstance(Map componentsCache, Component component, String name, List path, SubstituitionEntry entry) { - Optional ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); - if(ci.isPresent()){ - Either buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ci.get()); - if(buildSubstitutedName.isRight()){ - return false; - } - entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); - entry.setSourceName(buildSubstitutedName.left().value()); - } else { - return false; - } - return true; - } - - private void addEntry(Map toscaRequirements, Component component, List capPath, SubstituitionEntry entry) { - Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); - if (findFirst.isPresent()) { - entry.setOwner(findFirst.get().getNormalizedName()); - } - toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); - } - - private Either buildSubstitutedName(Map componentsCache, String name, List path, ComponentInstance instance) { - - Either result = null; - Either getOriginRes = getOriginComponent(componentsCache, instance); - if(getOriginRes.isRight()){ - logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); - result = Either.right(false); - } - if(result == null){ - List reducedPath = getReducedPath(path); - reducedPath.remove(reducedPath.size()-1); - result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); - } - return result; - } - - private String getRequirementPath(Component component, RequirementDefinition r) { - - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List capPath = r.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); - } - } - return ""; - } - - private ImmutablePair convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { - String name = r.getName(); - if (!isNodeType) { - name = getRequirementPath(component, r); - } - logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); - ToscaRequirement toscaRequirement = new ToscaRequirement(); - - List occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(r.getMinOccurrences())); - if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - occurences.add(r.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(r.getMaxOccurrences())); - } - toscaRequirement.setOccurrences(occurences); - toscaRequirement.setNode(r.getNode()); - toscaRequirement.setCapability(r.getCapability()); - toscaRequirement.setRelationship(r.getRelationship()); - - return new ImmutablePair<>(name, toscaRequirement); - } - - /** - * Allows to convert capabilities of a node type to tosca template capabilities - * @param component - * @param dataTypes - * @return - */ - public Map convertCapabilities(Component component, Map dataTypes) { - Map> capabilities = component.getCapabilities(); - Map toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry> entry : capabilities.entrySet()) { - entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert capabilities of a server proxy node type to tosca template capabilities - * @param component - * @param proxyComponent - * @param instanceProxy - * @param dataTypes - * @return - */ - public Map convertProxyCapabilities(Component component, Component proxyComponent, ComponentInstance instanceProxy, Map dataTypes) { - Map> capabilities = instanceProxy.getCapabilities(); - Map toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry> entry : capabilities.entrySet()) { - entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert component capabilities to the tosca template substitution mappings capabilities - * @param componentsCache - * @param component - * @return - */ - public Either, ToscaError> convertSubstitutionMappingCapabilities(Map componentsCache, Component component) { - Map> capabilities = component.getCapabilities(); - Either, ToscaError> res; - if (capabilities != null) { - res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); - } else { - res = Either.left(Maps.newHashMap()); - logger.debug(NO_CAPABILITIES); - } - return res; - } - - private String getCapabilityPath(CapabilityDefinition c, Component component) { - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List capPath = c.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); - } - } - return ""; - } - - private void convertCapabilty(Component component, Map toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map dataTypes) { - String name = c.getName(); - if (!isNodeType) { - name = getCapabilityPath(c, component); - } - logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); - ToscaCapability toscaCapability = new ToscaCapability(); - toscaCapability.setDescription(c.getDescription()); - toscaCapability.setType(c.getType()); - - List occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(c.getMinOccurrences())); - if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - occurences.add(c.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(c.getMaxOccurrences())); - } - toscaCapability.setOccurrences(occurences); - - toscaCapability.setValid_source_types(c.getValidSourceTypes()); - List properties = c.getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Map toscaProperties = new HashMap<>(); - for (PropertyDefinition property : properties) { - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); - toscaProperties.put(property.getName(), toscaProperty); - } - toscaCapability.setProperties(toscaProperties); - } - toscaCapabilities.put(name, toscaCapability); - } - /** - * Allows to build substituted name of capability\requirement of the origin component instance according to the path - * @param componentsCache - * @param originComponent - * @param path - * @param name - * @return - */ - public Either buildSubstitutedName(Map componentsCache, Component originComponent, List path, String name) { - StringBuilder substitutedName = new StringBuilder(); - boolean nameBuiltSuccessfully = true; - Either result; - if(CollectionUtils.isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ - List reducedPath = getReducedPath(path); - Collections.reverse(reducedPath); - nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); - } - if(nameBuiltSuccessfully){ - result = Either.left(substitutedName.append(name).toString()); - } else { - result = Either.right(nameBuiltSuccessfully); - } - return result; - } - - private List getReducedPath(List path) { - List pathCopy = Lists.newArrayList(); - path.stream().forEach(id -> {if(!pathCopy.contains(id))pathCopy.add(id);}); - return pathCopy; - } - - private boolean appendNameRecursively(Map componentsCache, Component originComponent, Iterator instanceIdIter, StringBuilder substitutedName) { - if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ - String instanceId = instanceIdIter.next(); - Optional instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instanceOpt.isPresent()){ - logger.debug("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); - return false; - } - substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); - Either getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); - if(getOriginRes.isRight()){ - return false; - } - appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); - } - return true; - } - - Either getOriginComponent(Map componentsCache, ComponentInstance instance) { - Either result; - Either getOriginRes; - if(componentsCache.containsKey(instance.getActualComponentUid())){ - result = Either.left(componentsCache.get(instance.getActualComponentUid())); - } else { - ComponentParametersView filter = getFilter(instance); - getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); - if(getOriginRes.isRight()){ - logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); - result = Either.right(false); - } else { - result = Either.left(getOriginRes.left().value()); - componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); - } - } - return result; - } - - private ComponentParametersView getFilter(ComponentInstance instance) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - if(instance.getIsProxy()){ - filter.setIgnoreCapabilities(false); - filter.setIgnoreRequirements(false); - } - return filter; - } - -} + + private static final String NO_CAPABILITIES = "No Capabilities for node type"; + private static CapabiltyRequirementConvertor instance; + private static final Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class); + public static final String PATH_DELIMITER = "."; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + protected CapabiltyRequirementConvertor() {} + + public static synchronized CapabiltyRequirementConvertor getInstance() { + if (instance == null) { + instance = new CapabiltyRequirementConvertor(); + } + return instance; + } + + public String buildCapabilityNameForComponentInstance( Map componentCache , ComponentInstance componentInstance, CapabilityDefinition c) { + + Either eitherName = buildSubstitutedName(componentCache, c.getName(), c.getPath(), c.getOwnerId(), componentInstance); + + return eitherName.isLeft() ? (String) eitherName.left().value() : c.getName() ; + } + + + /** + * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template + * @param componentInstance + * @param dataTypes + * @param nodeTemplate + * @return + */ + public Either convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map dataTypes, ToscaNodeTemplate nodeTemplate) { + + Map> capabilitiesInst = componentInstance.getCapabilities(); + Map componentCache = new HashMap<>(); + if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { + Map capabilities = new HashMap<>(); + capabilitiesInst.entrySet().forEach( e -> { + List capList = e.getValue(); + if ( capList != null && !capList.isEmpty() ) { + capList.forEach( c -> { + String capName = buildCapabilityNameForComponentInstance( componentCache , componentInstance , c ) ; + convertOverridenProperties( componentInstance, dataTypes, capabilities, c , capName ); + } ); + } + }); + if (MapUtils.isNotEmpty(capabilities)) { + nodeTemplate.setCapabilities(capabilities); + } + } + return Either.left(nodeTemplate); + } + + private void convertOverridenProperties(ComponentInstance componentInstance, Map dataTypes, Map capabilties, CapabilityDefinition c , String capabilityName) { + if (isNotEmpty(c.getProperties())) { + c.getProperties() + .stream() + .filter(p -> p.getValue() != null || p.getDefaultValue() != null) + .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName)); + } + } + + private void convertOverridenProperty(ComponentInstance componentInstance, Map dataTypes, Map capabilties, ComponentInstanceProperty p ,String capabilityName) { + if (logger.isDebugEnabled()) { + logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), capabilityName, p.getValue()); + } + ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() ); + + Map toscaCapProp = toscaTemplateCapability.getProperties(); + if (toscaCapProp == null) { + toscaCapProp = new HashMap<>(); + } + Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); + toscaCapProp.put(p.getName(), convertedValue); + toscaTemplateCapability.setProperties(toscaCapProp); + } + + private Object convertInstanceProperty(Map dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { + logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); + String propertyType = prop.getType(); + String innerType = null; + if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { + innerType = prop.getSchema().getProperty().getType(); + } + String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); + return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); + } + /** + * Allows to convert requirements of a node type to tosca template requirements representation + * @param component + * @param nodeType + * @return + */ + public Either convertRequirements(Component component, ToscaNodeType nodeType) { + List> toscaRequirements = convertRequirementsAsList(component); + if (!toscaRequirements.isEmpty()) { + nodeType.setRequirements(toscaRequirements); + } + logger.debug("Finish convert Requirements for node type"); + + return Either.left(nodeType); + } + + /** + * Allows to convert component requirements to the tosca template substitution mappings requirements + * @param componentsCache + * @param component + * @param substitutionMappings + * @return + */ + public Either convertSubstitutionMappingRequirements(Map componentsCache, Component component, SubstitutionMapping substitutionMappings) { + Either result = Either.left(substitutionMappings); + Either, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); + if(toscaRequirementsRes.isRight()){ + result = Either.right(toscaRequirementsRes.right().value()); + logger.error("Failed convert requirements for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { + substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); + result = Either.left(substitutionMappings); + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + return result; + } + + private List> convertRequirementsAsList(Component component) { + Map> requirements = component.getRequirements(); + List> toscaRequirements = new ArrayList<>(); + if (requirements != null) { + for (Map.Entry> entry : requirements.entrySet()) { + entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { + ImmutablePair pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); + Map requirement = new HashMap<>(); + + requirement.put(pair.left, pair.right); + toscaRequirements.add(requirement); + }); + logger.debug("Finish convert Requirements for node type"); + } + } else { + logger.debug("No Requirements for node type"); + } + return toscaRequirements; + } + + private boolean filter(Component component, String ownerId) { + return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); + } + + private boolean isNodeTypeOwner(Component component, String ownerId) { + return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); + } + + private String getSubPathByLastDelimiterAppearance(String path) { + return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); + } + + private String dropLast( String path, String delimiter ) { + if (isBlank(path) || isBlank(delimiter)){ + return path; + } + return path.substring(0, path.lastIndexOf(delimiter)); + } + + private Either, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map componentsCache, Component component) { + Map> requirements = component.getRequirements(); + Either, ToscaError> result; + if (requirements != null) { + result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); + } else { + result = Either.left(Maps.newHashMap()); + logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); + } + return result; + } + + private Either, ToscaError> buildAddSubstitutionMappingsRequirements(Map componentsCache, Component component, Map> requirements) { + + Map toscaRequirements = new HashMap<>(); + Either, ToscaError> result = null; + for (Map.Entry> entry : requirements.entrySet()) { + Optional failedToAddRequirement = entry.getValue() + .stream() + .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getOwnerId(), r.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private Either, ToscaError> buildAddSubstitutionMappingsCapabilities(Map componentsCache, Component component, Map> capabilities) { + + Map toscaRequirements = new HashMap<>(); + Either, ToscaError> result = null; + for (Map.Entry> entry : capabilities.entrySet()) { + Optional failedToAddRequirement = entry.getValue() + .stream() + .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getOwnerId(), c.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); + } + logger.debug("Finish convert capalilities for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private boolean addEntry(Map componentsCache, Map capReqMap, Component component, String name, String parentName, String ownerId, List path){ + + SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); + + if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, ownerId, entry)){ + return false; + } + logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); + if (entry.getSourceName() != null) { + addEntry(capReqMap, component, path, entry); + } + logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); + return true; + + } + + private boolean shouldBuildSubstitutionName(Component component, List path) { + return !ToscaUtils.isComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext(); + } + + private boolean buildSubstitutedNamePerInstance(Map componentsCache, Component component, String name, List path, String ownerId, SubstituitionEntry entry) { + Optional ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + if(!ci.isPresent()){ + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + + Collections.reverse(path); + + logger.error("try to reverse path {} component {}", path, component.getUniqueId()); + ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + } + if(ci.isPresent()){ + Either buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ownerId, ci.get()); + if(buildSubstitutedName.isRight()){ + logger.error("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId()); + return false; + } + entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); + entry.setSourceName(buildSubstitutedName.left().value()); + } else { + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + return false; + } + return true; + } + + private void addEntry(Map toscaRequirements, Component component, List capPath, SubstituitionEntry entry) { + Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); + if (findFirst.isPresent()) { + entry.setOwner(findFirst.get().getNormalizedName()); + } + toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); + } + + public Either buildSubstitutedName(Map componentsCache, String name, List path, String ownerId, ComponentInstance instance) { + + Either result = null; + Either getOriginRes = getOriginComponent(componentsCache, instance); + if(getOriginRes.isRight()){ + logger.error("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); + result = Either.right(false); + } + if(result == null){ + List reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ; + logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath); + reducedPath.remove(reducedPath.size()-1); + result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); + } + return result; + } + + private String getRequirementPath(Component component, RequirementDefinition r) { + + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List capPath = r.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); + } + } + return ""; + } + + private ImmutablePair convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { + String name = r.getName(); + if (!isNodeType) { + name = getRequirementPath(component, r); + } + logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); + ToscaRequirement toscaRequirement = new ToscaRequirement(); + + List occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(r.getMinOccurrences())); + if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + occurences.add(r.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(r.getMaxOccurrences())); + } + toscaRequirement.setOccurrences(occurences); + toscaRequirement.setNode(r.getNode()); + toscaRequirement.setCapability(r.getCapability()); + toscaRequirement.setRelationship(r.getRelationship()); + + return new ImmutablePair<>(name, toscaRequirement); + } + + /** + * Allows to convert capabilities of a node type to tosca template capabilities + * @param component + * @param dataTypes + * @return + */ + public Map convertCapabilities(Component component, Map dataTypes) { + Map> capabilities = component.getCapabilities(); + Map toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry> entry : capabilities.entrySet()) { + entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes , c.getName())); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert capabilities of a server proxy node type to tosca template capabilities + * @param component + * @param proxyComponent + * @param instanceProxy + * @param dataTypes + * @return + */ + public Map convertProxyCapabilities(Map componentCache, Component component, Component proxyComponent, ComponentInstance instanceProxy, Map dataTypes) { + Map> capabilities = instanceProxy.getCapabilities(); + Map toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry> entry : capabilities.entrySet()) { + entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes , buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c ))); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert component capabilities to the tosca template substitution mappings capabilities + * @param componentsCache + * @param component + * @return + */ + public Either, ToscaError> convertSubstitutionMappingCapabilities(Map componentsCache, Component component) { + Map> capabilities = component.getCapabilities(); + Either, ToscaError> res; + if (capabilities != null) { + res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); + } else { + res = Either.left(Maps.newHashMap()); + logger.debug(NO_CAPABILITIES); + } + return res; + } + + private String getCapabilityPath(CapabilityDefinition c, Component component) { + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List capPath = c.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); + } + } + return ""; + } + + private void convertCapabilty(Component component, Map toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map dataTypes , String capabilityName) { + String name = isNoneBlank(capabilityName) ? capabilityName : c.getName(); + if (!isNodeType) { + name = getCapabilityPath(c, component); + } + logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); + ToscaCapability toscaCapability = new ToscaCapability(); + toscaCapability.setDescription(c.getDescription()); + toscaCapability.setType(c.getType()); + + List occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(c.getMinOccurrences())); + if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + occurences.add(c.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(c.getMaxOccurrences())); + } + toscaCapability.setOccurrences(occurences); + + toscaCapability.setValid_source_types(c.getValidSourceTypes()); + List properties = c.getProperties(); + if (isNotEmpty(properties)) { + Map toscaProperties = new HashMap<>(); + for (PropertyDefinition property : properties) { + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + toscaProperties.put(property.getName(), toscaProperty); + } + toscaCapability.setProperties(toscaProperties); + } + toscaCapabilities.put(name, toscaCapability); + } + /** + * Allows to build substituted name of capability\requirement of the origin component instance according to the path + * @param componentsCache + * @param originComponent + * @param path + * @param name + * @return + */ + public Either buildSubstitutedName(Map componentsCache, Component originComponent, List path, String name) { + StringBuilder substitutedName = new StringBuilder(); + boolean nameBuiltSuccessfully = true; + Either result; + if(isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ + List reducedPath = getReducedPath(path); + Collections.reverse(reducedPath); + nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); + } + if(nameBuiltSuccessfully){ + result = Either.left(substitutedName.append(name).toString()); + } else { + result = Either.right(nameBuiltSuccessfully); + } + return result; + } + + protected List getReducedPathByOwner(List path , String ownerId) { + logger.debug("ownerId {}, path {} ", ownerId, path); + if ( CollectionUtils.isEmpty(path) ){ + logger.debug("cannot perform reduce by owner, path to component is empty"); + return path; + } + if ( isBlank(ownerId) ){ + logger.debug("cannot perform reduce by owner, component owner is empty"); + return path; + } + //reduce by owner + Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) -> a.endsWith(ownerId) ? a : b )); + //reduce list&duplicates and preserve order + return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList()); + } + + private List getReducedPath(List path) { + return path.stream().distinct().collect(Collectors.toList()); + } + + private boolean appendNameRecursively(Map componentsCache, Component originComponent, Iterator instanceIdIter, StringBuilder substitutedName) { + if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ + String instanceId = instanceIdIter.next(); + Optional instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instanceOpt.isPresent()){ + logger.error("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); + return false; + } + substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); + Either getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); + if(getOriginRes.isRight()){ + return false; + } + appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); + } + return true; + } + + Either getOriginComponent(Map componentsCache, ComponentInstance instance) { + Either result; + Either getOriginRes; + if(componentsCache.containsKey(instance.getActualComponentUid())){ + result = Either.left(componentsCache.get(instance.getActualComponentUid())); + } else { + ComponentParametersView filter = getFilter(instance); + getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); + if(getOriginRes.isRight()){ + logger.error("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); + result = Either.right(false); + } else { + result = Either.left(getOriginRes.left().value()); + componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); + } + } + return result; + } + + private ComponentParametersView getFilter(ComponentInstance instance) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + if(instance.getIsProxy()){ + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreCategories(false); + } + return filter; + } + +} \ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index f6ae79b26a..ed3a2462bd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -103,1458 +103,1466 @@ import fj.data.Either; */ @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { - private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName()); - - @Autowired - private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - @Autowired - private ComponentsUtils componentsUtils; - @Autowired - private ToscaExportHandler toscaExportUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - private Gson gson = new Gson(); - - public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); - - public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); - public static final String ARTIFACTS_PATH = "Artifacts/"; - public static final String RESOURCES_PATH = "Resources/"; - public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; - public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; - - public static final String DEFINITIONS_PATH = "Definitions/"; - private static final String CSAR_META_VERSION = "1.0"; - private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; - private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; - private static final String TOSCA_META_VERSION = "1.0"; - private static final String CSAR_VERSION = "1.1"; - public static final String ARTIFACTS = "Artifacts"; - public static final String DEFINITION = "Definitions"; - public static final String DEL_PATTERN = "([/\\\\]+)"; - private static String versionFirstThreeOctates; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + - ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)"; - - public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ - // Artifact Group (i.e Deployment/Informational) - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Type - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Any File Name - ".+"; - public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + @Autowired + private ComponentsUtils componentsUtils; + @Autowired + private ToscaExportHandler toscaExportUtils; + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + private Gson gson = new Gson(); + + public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); + + public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String RESOURCES_PATH = "Resources/"; + public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; + public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; + + public static final String DEFINITIONS_PATH = "Definitions/"; + private static final String CSAR_META_VERSION = "1.0"; + private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; + private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; + private static final String TOSCA_META_VERSION = "1.0"; + private static final String CSAR_VERSION = "1.1"; + public static final String ARTIFACTS = "Artifacts"; + public static final String DEFINITION = "Definitions"; + public static final String DEL_PATTERN = "([/\\\\]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)"; + + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ + // Artifact Group (i.e Deployment/Informational) + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Type + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Any File Name + ".+"; + public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+ // Service Template File Name "([\\w\\_\\-\\.\\s]+)"; public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; - public CsarUtils() { - if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - versionFirstThreeOctates = matcher.group(0); - } else { - versionFirstThreeOctates = ""; - } - } - - /** - * - * @param component - * @param getFromCS - * @param isInCertificationRequest - * @return - */ - public Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { - return createCsar(component, getFromCS, isInCertificationRequest, false); - } - - private Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - final String createdBy = component.getCreatorFullName(); - - String fileName; - Map toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - fileName = artifactDefinition.getArtifactName(); - - String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); - byte[] csarBlock0Byte = csarBlock0.getBytes(); - - final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); - byte[] toscaBlock0Byte = toscaBlock0.getBytes(); - - Either generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); - - if (generateCsarZipResponse.isRight()) { - return Either.right(generateCsarZipResponse.right().value()); - } - - return Either.left(generateCsarZipResponse.left().value()); - } - - private Either generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - try ( - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(out); - ){ - zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); - zip.write(csarBlock0Byte); - zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); - zip.write(toscaBlock0Byte); - Either populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); - if (populateZip.isRight()) { - log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); - return Either.right(populateZip.right().value()); - } - - zip.finish(); - byte[] byteArray = out.toByteArray(); - - return Either.left(byteArray); - } catch (IOException e) { - log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - private Either populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { - - LifecycleStateEnum lifecycleState = component.getLifecycleState(); - String componentYaml; - Either exportComponent; - byte[] mainYaml; - // - List> dependencies = null; - List> generatorInputs = new LinkedList<>(); - - Map toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - String fileName = artifactDefinition.getArtifactName(); - - if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - String cassandraId = artifactDefinition.getEsId(); - Either fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { + public CsarUtils() { + if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + + /** + * + * @param component + * @param getFromCS + * @param isInCertificationRequest + * @return + */ + public Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { + return createCsar(component, getFromCS, isInCertificationRequest, false); + } + + private Either createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + final String createdBy = component.getCreatorFullName(); + + String fileName; + Map toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + fileName = artifactDefinition.getArtifactName(); + + String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); + byte[] csarBlock0Byte = csarBlock0.getBytes(); + + final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); + byte[] toscaBlock0Byte = toscaBlock0.getBytes(); + + Either generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); + + if (generateCsarZipResponse.isRight()) { + return Either.right(generateCsarZipResponse.right().value()); + } + + return Either.left(generateCsarZipResponse.left().value()); + } + + private Either generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + try ( + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(out); + ){ + zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); + zip.write(csarBlock0Byte); + zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); + zip.write(toscaBlock0Byte); + Either populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); + if (populateZip.isRight()) { + log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); + return Either.right(populateZip.right().value()); + } + + zip.finish(); + byte[] byteArray = out.toByteArray(); + + return Either.left(byteArray); + } catch (IOException e) { + log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + private Either populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { + + LifecycleStateEnum lifecycleState = component.getLifecycleState(); + String componentYaml; + Either exportComponent; + byte[] mainYaml; + // + List> dependencies = null; + List> generatorInputs = new LinkedList<>(); + + Map toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + String fileName = artifactDefinition.getArtifactName(); + + if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + String cassandraId = artifactDefinition.getEsId(); + Either fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); - return Either.right(responseFormat); - } - mainYaml = fromCassandra.left().value(); - - } else { - exportComponent = toscaExportUtils.exportComponent(component); - if (exportComponent.isRight()) { - log.debug("exportComponent failed", exportComponent.right().value()); - ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); - return Either.right(responseFormat); - } - ToscaRepresentation exportResult = exportComponent.left().value(); - componentYaml = exportResult.getMainYaml(); - mainYaml = componentYaml.getBytes(); - dependencies = exportResult.getDependencies(); - } - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(mainYaml); - //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)){ - log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - writeComponentInterface(component, zip, fileName); - } - - generatorInputs.add(new ImmutablePair(component, mainYaml)); - - if (dependencies == null) { - Either dependenciesRes = toscaExportUtils.getDependencies(component); - if (dependenciesRes.isRight()) { - log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), - dependenciesRes.right().value()); - ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); - return Either.right(responseFormat); - } - dependencies = dependenciesRes.left().value().getDependencies(); - } - - //UID - Map> innerComponentsCache = new HashMap<>(); - - if (dependencies != null && !dependencies.isEmpty()) { - for (Triple d : dependencies) { - String cassandraId = d.getMiddle(); - Component childComponent = d.getRight(); - Either entryData = getEntryData(cassandraId, childComponent); - - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - return Either.right(responseFormat); - } - - //fill innerComponentsCache - fileName = d.getLeft(); - addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); - addInnerComponentsToCache(innerComponentsCache, childComponent); - - byte[] content = entryData.left().value(); - generatorInputs.add(new ImmutablePair(childComponent, content)); - } - - //add inner components to CSAR - for (Entry> innerComponentTripleEntry : innerComponentsCache.entrySet()) { - - ImmutableTriple innerComponentTriple = innerComponentTripleEntry.getValue(); - - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - // add component to zip - Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), - entryData.right().value()); - return Either.right(responseFormat); - } - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - // add component interface to zip - if (!ModelConverter.isAtomicComponent(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - } - } - - //retrieve SDC.zip from Cassandra - Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); - - if(latestSchemaFilesFromCassandra.isRight()){ - log.error("Error retrieving SDC Schema files from cassandra" ); - return Either.right(latestSchemaFilesFromCassandra.right().value()); - } - - //add files from retireved SDC.zip to Definitions folder in CSAR - Either addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - - if(addSchemaFilesFromCassandra.isRight()){ - return addSchemaFilesFromCassandra; - } - - // Artifact Generation - if (component.getComponentType() == ComponentTypeEnum.SERVICE - && isInCertificationRequest) { - - List aiiArtifactList; - - Either, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); - - if (handleAAIArtifacts.isLeft()) { - aiiArtifactList = handleAAIArtifacts.left().value(); - } else { - log.debug("AAI Artifacts handling failed"); - return Either.right(handleAAIArtifacts.right().value()); - } - - if (isInCertificationRequest) { - Either handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( - component, aiiArtifactList, false, true); - - if (handleAllAAIArtifactsInDataModel.isRight()) { - log.debug("AAI Artifacts handling (create, update, delete) failed"); - return Either.right(handleAllAAIArtifactsInDataModel.right().value()); - } - } - - } - - Either collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - - if (collectedComponentCsarDefinition.isRight()) { - return Either.right(collectedComponentCsarDefinition.right().value()); - } - - return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); - } - - private Either addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - - final int initSize = 2048; - - log.debug("Starting copy from Schema file zip to CSAR zip"); - - try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - - ZipEntry entry = null; - - while ((entry = zipStream.getNextEntry()) != null) { - - String entryName = entry.getName(); - int readSize = initSize; - byte[] entryData = new byte[initSize]; - - while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { - bos.write(entryData, 0, readSize); - } - - bos.flush(); - out.flush(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); - zip.write(out.toByteArray()); - zip.flush(); - out.reset(); - } - } catch (IOException e) { - log.error("Error while writing the SDC schema file to the CSAR {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - log.debug("Finished coppy from Schema file zip to CSAR zip"); - - return Either.left(zip); - } - - - private void addInnerComponentsToCache(Map> componentCache, - Component childComponent) { - - List instances = childComponent.getComponentInstances(); - - if(instances != null) { - instances.forEach(ci -> { - ImmutableTriple componentRecord = componentCache.get(ci.getComponentUid()); - if (componentRecord == null) { - // all resource must be only once! - Either resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component componentRI = resource.left().value(); - - Map childToscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - if (childArtifactDefinition != null) { - //add to cache - addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); - } - - //if not atomic - insert inner components as well - if(!ModelConverter.isAtomicComponent(componentRI)) { - addInnerComponentsToCache(componentCache, componentRI); - } - } - }); - } - } - - private void addComponentToCache(Map> componentCache, - String id, String fileName, Component component) { - - ImmutableTriple cachedComponent = componentCache.get(component.getInvariantUUID()); - if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { - componentCache.put(component.getInvariantUUID(), - new ImmutableTriple(id, fileName, component)); - - if(cachedComponent != null) { - //overwriting component with newer version - log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); - } - } - } - - private Either writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { - try { - Either componentInterface = toscaExportUtils.exportComponentInterface(component); - ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); - String mainYaml = componentInterfaceYaml.getMainYaml(); - String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); - - zip.putNextEntry(new ZipEntry(interfaceFileName)); - zip.write(mainYaml.getBytes()); - - } catch (Exception e) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - return Either.left(zip); - } - - private Either, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List> generatorInputs) { - - ComponentTypeEnum componentType = component.getComponentType(); - List generatedArtifacts; - List aaiArtifacts = new LinkedList<>(); - - if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { - List convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); - - Either, String> generatorResponse; - - if (mockGenerator) { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); - } else { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); - } - - if (generatorResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); - return Either.right(responseFormat); - } - - generatedArtifacts = generatorResponse.left().value(); - - aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); - - } - - return Either.left(aaiArtifacts); - } - - private Either handleAllAAIArtifactsInDataModel(Component component, List artifactsFromAAI, boolean shouldLock, boolean inTransaction) { - - Either handleAAIArtifactsResponse; - User lastComponentUpdater; - - List aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); - List aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); - List aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); - - String lastUpdaterUserId = component.getLastUpdaterUserId(); - Either validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); - - if (validateUserExists.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); - return Either.right(responseFormat); - } - - lastComponentUpdater = validateUserExists.left().value(); - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction); - } - - private List getAAIArtifatcsForUpdate(List artifactsFromAAI, Component component) { - - Set componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); - Set componetInformationalArtifactLables = component.getArtifacts().keySet(); - - return artifactsFromAAI.stream() - .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) - .filter(e -> checkAaiForUpdate(component, e)) - .collect(Collectors.toList()); - } - - private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { - ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); - - if (artifactDefinitionComp == null) { - log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); - return false; - } - - // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated - if (artifactDefinitionComp.getGenerated() == null) { - if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { - return true; - } else { - log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); - } - } else { - if (artifactDefinition.getGenerated()) { - return true; - } else { - log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); - } - } - return false; - } - - private List getAAIArtifatcsForDelete(List artifactsFromAAI, Component component) { - - Set aaiLabels = artifactsFromAAI.stream() - .map(ArtifactDefinition::getArtifactLabel) - .collect(Collectors.toSet()); - - List artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - List artifactsForDeleteInformational = component.getArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); - - return artifactsForDeleteDeployment.stream() - .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) - .collect(Collectors.toList()); - } - - private List getAAIArtifatcsForCreate(List artifactsFromAAI, Component component) { - - Set componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); - Set componentInfoLabels = component.getArtifacts().keySet(); - - // If the artifact label does not exist in the service - - // store the artifact (generate uuid and version, "generated" flag is TRUE) - return artifactsFromAAI.stream() - .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - } - - private Either handleAAIArtifactsInDataModelByOperationType(Component component, List generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, - boolean inTransaction) { - - String componentUniqueId = component.getUniqueId(); - ComponentTypeEnum componentType = component.getComponentType(); - - for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { - String data = gson.toJson(artDef); - String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); - String artifactUniqueId = null; - - if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) { - String artifactLabel = artDef.getArtifactLabel(); - ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); - if (artifactDefinition != null) { - artifactUniqueId = artifactDefinition.getUniqueId(); - } - } - - Either, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, - null, null, user, component, shouldLock, inTransaction, false); - - if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); - - Either.right(responseFormat); - } else { - log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); - } - } - } - - return Either.left(ActionStatus.OK); - } - - private List convertToArtifactDefinitionFromArtifactGeneratedData(List generatorOutput) { - List artifactDefList = new LinkedList<>(); - - for (Artifact artifact : generatorOutput) { - ArtifactDefinition newEntry = new ArtifactDefinition(); - newEntry.setArtifactName(artifact.getName()); - newEntry.setArtifactType(artifact.getType()); - newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); - newEntry.setDescription(artifact.getDescription()); - - // Normalizing the artifact label to match those stored in DB - String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); - newEntry.setArtifactLabel(normalizeArtifactLabel); - newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); - newEntry.setArtifactChecksum(artifact.getChecksum()); - // Flag that set to true in case that the artifact is generated by AI&I generator - newEntry.setGenerated(Boolean.TRUE); - - artifactDefList.add(newEntry); - } - - return artifactDefList; - } - - // List> - // artifact stored by label - private List convertToGeneratorArtifactsInput(List> inputs) { - List listOfArtifactsInput = new LinkedList<>(); - for (ImmutablePair triple : inputs) { - Component component = triple.getLeft(); - - Map toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - String artifactName = artifactDefinition.getArtifactName(); - String artifactType = artifactDefinition.getArtifactType(); - String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); - String artifactDescription = artifactDefinition.getDescription(); - String artifactLabel = artifactDefinition.getArtifactLabel(); - byte[] right = triple.getRight(); - // The md5 calculated on the uncoded data - String md5Hex = DigestUtils.md5Hex(right); - byte[] payload = Base64.encodeBase64(right); - String artifactVersion = artifactDefinition.getArtifactVersion(); - - Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); - convertedArtifact.setName(artifactName); - convertedArtifact.setDescription(artifactDescription); - convertedArtifact.setLabel(artifactLabel); - convertedArtifact.setVersion(artifactVersion); - - listOfArtifactsInput.add(convertedArtifact); - } - - return listOfArtifactsInput; - } - - private Either getEntryData(String cassandraId, Component childComponent) { - byte[] content; - if (cassandraId == null || cassandraId.isEmpty()) { - Either exportRes = toscaExportUtils.exportComponent(childComponent); - if (exportRes.isRight()) { - log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); - return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); - } - content = exportRes.left().value().getMainYaml().getBytes(); - } else { - Either fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); - } else { - content = fromCassandra.left().value(); - } - } - return Either.left(content); - } - - private Either getLatestSchemaFilesFromCassandra() { - Either, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); - } - - List listOfSchemas = specificSchemaFiles.left().value(); - - if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); - } - - SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); - - return Either.left(schemaFile.getPayloadAsArray()); - } - - private Either getFromCassandra(String cassandraId) { - Either artifactResponse = artifactCassandraDao.getArtifact(cassandraId); - - if (artifactResponse.isRight()) { - log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); - - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(convertedFromStorageResponse); - } - ESArtifactData artifactData = artifactResponse.left().value(); - return Either.left(artifactData.getDataAsArray()); - } - - private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { - final String BLOCK_0_TEMPLATE = - "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; - String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); - return readyBlock; - } - - private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; - return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); - } - - private Either, String> artifactGenerator(List artifactList, ArtifactType type, Component component) { - - ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); - ArtifactTypes artifactTypes = new ArtifactTypes(); - List artifactTypesList = new LinkedList<>(); - ArtifactType otherType; - - if (type == null) { - otherType = ArtifactType.OTHER; - } else { - otherType = type; - } - - artifactTypesList.add(otherType); - artifactTypes.setArtifactTypes(artifactTypesList); - - String configJson = gson.toJson(artifactTypes); - Map additionalParams = new HashMap<>(); - String version; - - if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { - version = component.getVersion(); - } else { - String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; - } - - additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); - GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); - - Map> errorData = generatedArtifacts.getErrorData(); - - if (!errorData.isEmpty()) { - Set keySet = errorData.keySet(); - StringBuilder error = new StringBuilder(); - - for (String key : keySet) { - List errorList = errorData.get(key); - log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); - error.append(key + errorList); - } - - return Either.right(error.toString()); - } - - return Either.left(generatedArtifacts.getResultData()); - } - - /** - * Extracts artifacts of VFCs from CSAR - * - * @param csar - * @return Map of > the contains Lists of artifacts according vfcToscaNamespace - */ - public static Map> extractVfcsArtifactsFromCsar(Map csar) { - - Map> artifacts = new HashMap<>(); - if (csar != null) { - log.debug("************* Going to extract VFCs artifacts from Csar. "); - Map>> collectedWarningMessages = new HashMap<>(); - csar.entrySet().stream() - // filter CSAR entry by node type artifact path - .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path - .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); - // add counter suffix to artifact labels - handleWarningMessages(collectedWarningMessages); - - } - return artifacts; - } - - /** - * Print warnings to log - * - * @param collectedWarningMessages - */ - public static void handleWarningMessages(Map>> collectedWarningMessages) { - collectedWarningMessages.entrySet().stream() - // for each vfc - .forEach(e -> e.getValue().stream() - // add each warning message to log - .forEach(args -> log.warn(e.getKey(), args.toArray()))); - - } - - private static void addExtractedVfcArtifact(ImmutablePair extractedVfcArtifact, Map> artifacts) { - if (extractedVfcArtifact != null) { - List currArtifactsList; - String vfcToscaNamespace = extractedVfcArtifact.getKey(); - if (artifacts.containsKey(vfcToscaNamespace)) { - currArtifactsList = artifacts.get(vfcToscaNamespace); - } else { - currArtifactsList = new ArrayList<>(); - artifacts.put(vfcToscaNamespace, currArtifactsList); - } - currArtifactsList.add(extractedVfcArtifact.getValue()); - } - } - - private static ImmutablePair extractVfcArtifact(Entry entry, Map>> collectedWarningMessages) { - ArtifactDefinition artifact; - String[] parsedCsarArtifactPath = entry.getKey().split("/"); - Either eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); - if (eitherArtifactGroupType.isLeft()) { - artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); - } else { - return null; - } - return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); - } - - private static Either detectArtifactGroupType(String groupType, Map>> collectedWarningMessages) { - Either result; - try { - ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); - if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { - String warningMessage = "Warning - unrecognized artifact group type {} was received."; - List messageArguments = new ArrayList<>(); - messageArguments.add(groupType); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - - result = Either.right(false); - } else { - - result = Either.left(artifactGroupType); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - result = Either.right(false); - } - return result; - } - - private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry entry, Map>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { - ArtifactDefinition artifact; - artifact = new ArtifactDefinition(); - artifact.setArtifactGroupType(artifactGroupType); - artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); - artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); - artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); - artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); - artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); - artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); - artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); - return artifact; - } - - public static final class NonMetaArtifactInfo { - private final String path; - private final String artifactName; - private final String displayName; - private final String artifactLabel; - private final ArtifactTypeEnum artifactType; - private final ArtifactGroupTypeEnum artifactGroupType; - private String payloadData; - private String artifactChecksum; - private String artifactUniqueId; - - public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) { - super(); - this.path = path; - this.artifactName = ValidationUtils.normalizeFileName(artifactName); - this.artifactType = artifactType; - this.artifactGroupType = artifactGroupType; - final int pointIndex = artifactName.lastIndexOf('.'); - if (pointIndex > 0) { - displayName = artifactName.substring(0, pointIndex); - } else { - displayName = artifactName; - } - this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); - if (payloadData != null) { - this.payloadData = Base64.encodeBase64String(payloadData); - this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); - } - this.artifactUniqueId = artifactUniqueId; - } - - public String getPath() { - return path; - } - - public String getArtifactName() { - return artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public String getDisplayName() { - return displayName; - } - - public ArtifactGroupTypeEnum getArtifactGroupType() { - return artifactGroupType; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public String getPayloadData() { - return payloadData; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public String getArtifactUniqueId() { - return artifactUniqueId; - } - - public void setArtifactUniqueId(String artifactUniqueId) { - this.artifactUniqueId = artifactUniqueId; - } - - } - - /** - * This method checks the artifact GroupType & Artifact Type.
- * if there is any problem warning messages are added to collectedWarningMessages - * - * @param artifactPath - * @param collectedWarningMessages - * @return - */ - public static Either validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map>> collectedWarningMessages) { - Either ret; - try { - String[] parsedArtifactPath = artifactPath.split("/"); - // Validate Artifact Group Type - Either eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); - if (eitherGroupType.isLeft()) { - final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); - - // Validate Artifact Type - String artifactType = parsedArtifactPath[2]; - artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); - - String artifactFileNameType = parsedArtifactPath[3]; - ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null)); - - } else { - ret = Either.right(eitherGroupType.right().value()); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - ret = Either.right(false); - } - return ret; - - } - - private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); - } - - private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); - } - - private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map>> collectedWarningMessages, String... arguments) { - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); - Map resourceValidTypeArtifacts = null; - - if(artifactGroupType != null){ - switch (artifactGroupType) { - case INFORMATIONAL: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceInformationalArtifacts(); - break; - case DEPLOYMENT: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceDeploymentArtifacts(); - break; - default: - break; - } - } - - Set validArtifactTypes = null; - if(resourceValidTypeArtifacts != null){ - validArtifactTypes = resourceValidTypeArtifacts.keySet(); - } - - if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { - List messageArguments = new ArrayList<>(); - messageArguments.add(receivedTypeName); - messageArguments.addAll(Arrays.asList(arguments)); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - } - - return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); - } - - private Either writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ - ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); - - Either writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - Map componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); - Set keySet = componentInstancesArtifacts.keySet(); - - String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; - for (String keyAssetName : keySet) { - ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); - String pathWithAssetName = currentPath + keyAssetName + "/"; - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - } - - return Either.left(zipstream); - } - - private Either writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, - String currentPath, boolean isInCertificationRequest) throws IOException { - Map componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); - //Keys are defined: - // folder name: _v. - //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" - Set componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); - for (String keyAssetName : componentTypeArtifactsKeys) { - ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); - ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); - String pathWithAssetName = currentPath + keyAssetName + "/"; - Either writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeArtifactsInfoToSpecifiedtPath.isRight()){ - return writeArtifactsInfoToSpecifiedtPath; - } - } - - return Either.left(zipstream); - } - - private Either writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { - Map>> artifactsInfo = currArtifactsInfo - .getArtifactsInfo(); - Set groupTypeEnumKeySet = artifactsInfo.keySet(); - - for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { - String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; - - Map> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); - Set artifactTypeEnumKeySet = artifactTypesMap.keySet(); - - for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { - List artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); - String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; - - Either writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); - - if(writeArtifactDefinition.isRight()){ - return writeArtifactDefinition; - } - } - } - - return Either.left(zip); - } - - private Either writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List artifactDefinitionList, - String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { - - ComponentTypeEnum componentType = mainComponent.getComponentType(); - String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); - - for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { - if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE - && artifactDefinition.getArtifactType().equals(heatEnvType) || + return Either.right(responseFormat); + } + mainYaml = fromCassandra.left().value(); + + } else { + exportComponent = toscaExportUtils.exportComponent(component); + if (exportComponent.isRight()) { + log.debug("exportComponent failed", exportComponent.right().value()); + ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); + return Either.right(responseFormat); + } + ToscaRepresentation exportResult = exportComponent.left().value(); + componentYaml = exportResult.getMainYaml(); + mainYaml = componentYaml.getBytes(); + dependencies = exportResult.getDependencies(); + } + + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); + zip.write(mainYaml); + //US798487 - Abstraction of complex types + if (!ModelConverter.isAtomicComponent(component)){ + log.debug("Component {} is complex - generating abstract type for it..", component.getName()); + writeComponentInterface(component, zip, fileName); + } + + generatorInputs.add(new ImmutablePair(component, mainYaml)); + + if (dependencies == null) { + Either dependenciesRes = toscaExportUtils.getDependencies(component); + if (dependenciesRes.isRight()) { + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), + dependenciesRes.right().value()); + ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + return Either.right(responseFormat); + } + dependencies = dependenciesRes.left().value().getDependencies(); + } + + //UID + Map> innerComponentsCache = new HashMap<>(); + + if (dependencies != null && !dependencies.isEmpty()) { + for (Triple d : dependencies) { + String cassandraId = d.getMiddle(); + Component childComponent = d.getRight(); + Either entryData = getEntryData(cassandraId, childComponent); + + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + return Either.right(responseFormat); + } + + //fill innerComponentsCache + fileName = d.getLeft(); + addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); + addInnerComponentsToCache(innerComponentsCache, childComponent); + + byte[] content = entryData.left().value(); + generatorInputs.add(new ImmutablePair(childComponent, content)); + } + + //add inner components to CSAR + for (Entry> innerComponentTripleEntry : innerComponentsCache.entrySet()) { + + ImmutableTriple innerComponentTriple = innerComponentTripleEntry.getValue(); + + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); + + // add component to zip + Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), + entryData.right().value()); + return Either.right(responseFormat); + } + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ModelConverter.isAtomicComponent(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } + } + + //retrieve SDC.zip from Cassandra + Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + + if(latestSchemaFilesFromCassandra.isRight()){ + log.error("Error retrieving SDC Schema files from cassandra" ); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } + + //add files from retireved SDC.zip to Definitions folder in CSAR + Either addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); + + if(addSchemaFilesFromCassandra.isRight()){ + return addSchemaFilesFromCassandra; + } + + // Artifact Generation + if (component.getComponentType() == ComponentTypeEnum.SERVICE + && isInCertificationRequest) { + + List aiiArtifactList; + + Either, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); + + if (handleAAIArtifacts.isLeft()) { + aiiArtifactList = handleAAIArtifacts.left().value(); + } else { + log.debug("AAI Artifacts handling failed"); + return Either.right(handleAAIArtifacts.right().value()); + } + + if (isInCertificationRequest) { + Either handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( + component, aiiArtifactList, false, true); + + if (handleAllAAIArtifactsInDataModel.isRight()) { + log.debug("AAI Artifacts handling (create, update, delete) failed"); + return Either.right(handleAllAAIArtifactsInDataModel.right().value()); + } + } + + } + + Either collectedComponentCsarDefinition = collectComponentCsarDefinition(component); + + if (collectedComponentCsarDefinition.isRight()) { + return Either.right(collectedComponentCsarDefinition.right().value()); + } + + return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); + } + + private Either addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ + + final int initSize = 2048; + + log.debug("Starting copy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { + + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); + } + } catch (IOException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + log.debug("Finished coppy from Schema file zip to CSAR zip"); + + return Either.left(zip); + } + + + private void addInnerComponentsToCache(Map> componentCache, + Component childComponent) { + + List instances = childComponent.getComponentInstances(); + + if(instances != null) { + instances.forEach(ci -> { + ImmutableTriple componentRecord = componentCache.get(ci.getComponentUid()); + if (componentRecord == null) { + // all resource must be only once! + Either resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); + if (resource.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } + Component componentRI = resource.left().value(); + + Map childToscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + if (childArtifactDefinition != null) { + //add to cache + addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); + } + + //if not atomic - insert inner components as well + if(!ModelConverter.isAtomicComponent(componentRI)) { + addInnerComponentsToCache(componentCache, componentRI); + } + } + }); + } + } + + private void addComponentToCache(Map> componentCache, + String id, String fileName, Component component) { + + ImmutableTriple cachedComponent = componentCache.get(component.getInvariantUUID()); + if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { + componentCache.put(component.getInvariantUUID(), + new ImmutableTriple(id, fileName, component)); + + if(cachedComponent != null) { + //overwriting component with newer version + log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); + } + } + } + + private Either writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { + try { + Either componentInterface = toscaExportUtils.exportComponentInterface(component); + ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); + String mainYaml = componentInterfaceYaml.getMainYaml(); + String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); + + zip.putNextEntry(new ZipEntry(interfaceFileName)); + zip.write(mainYaml.getBytes()); + + } catch (Exception e) { + log.error("#writeComponentInterface - zip writing failed with error: ", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return Either.left(zip); + } + + private Either, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List> generatorInputs) { + + ComponentTypeEnum componentType = component.getComponentType(); + List generatedArtifacts; + List aaiArtifacts = new LinkedList<>(); + + if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { + List convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); + + Either, String> generatorResponse; + + if (mockGenerator) { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); + } else { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); + } + + if (generatorResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); + return Either.right(responseFormat); + } + + generatedArtifacts = generatorResponse.left().value(); + + aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); + + } + + return Either.left(aaiArtifacts); + } + + private Either handleAllAAIArtifactsInDataModel(Component component, List artifactsFromAAI, boolean shouldLock, boolean inTransaction) { + + Either handleAAIArtifactsResponse; + User lastComponentUpdater; + + List aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); + List aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); + List aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); + + String lastUpdaterUserId = component.getLastUpdaterUserId(); + Either validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); + + if (validateUserExists.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); + return Either.right(responseFormat); + } + + lastComponentUpdater = validateUserExists.left().value(); + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction); + } + + private List getAAIArtifatcsForUpdate(List artifactsFromAAI, Component component) { + + Set componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); + Set componetInformationalArtifactLables = component.getArtifacts().keySet(); + + return artifactsFromAAI.stream() + .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) + .filter(e -> checkAaiForUpdate(component, e)) + .collect(Collectors.toList()); + } + + private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { + ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); + + if (artifactDefinitionComp == null) { + log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); + return false; + } + + // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated + if (artifactDefinitionComp.getGenerated() == null) { + if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { + return true; + } else { + log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); + } + } else { + if (artifactDefinition.getGenerated()) { + return true; + } else { + log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); + } + } + return false; + } + + private List getAAIArtifatcsForDelete(List artifactsFromAAI, Component component) { + + Set aaiLabels = artifactsFromAAI.stream() + .map(ArtifactDefinition::getArtifactLabel) + .collect(Collectors.toSet()); + + List artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + List artifactsForDeleteInformational = component.getArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); + + return artifactsForDeleteDeployment.stream() + .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) + .collect(Collectors.toList()); + } + + private List getAAIArtifatcsForCreate(List artifactsFromAAI, Component component) { + + Set componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); + Set componentInfoLabels = component.getArtifacts().keySet(); + + // If the artifact label does not exist in the service - + // store the artifact (generate uuid and version, "generated" flag is TRUE) + return artifactsFromAAI.stream() + .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + } + + private Either handleAAIArtifactsInDataModelByOperationType(Component component, List generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, + boolean inTransaction) { + + String componentUniqueId = component.getUniqueId(); + ComponentTypeEnum componentType = component.getComponentType(); + + for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { + String data = gson.toJson(artDef); + String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); + String artifactUniqueId = null; + + if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) { + String artifactLabel = artDef.getArtifactLabel(); + ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); + if (artifactDefinition != null) { + artifactUniqueId = artifactDefinition.getUniqueId(); + } + } + + Either, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, + null, user, component, shouldLock, inTransaction, false); + + if (validateAndHandleArtifact.isRight()) { + if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); + + Either.right(responseFormat); + } else { + log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); + } + } + } + + return Either.left(ActionStatus.OK); + } + + private List convertToArtifactDefinitionFromArtifactGeneratedData(List generatorOutput) { + List artifactDefList = new LinkedList<>(); + + for (Artifact artifact : generatorOutput) { + ArtifactDefinition newEntry = new ArtifactDefinition(); + newEntry.setArtifactName(artifact.getName()); + newEntry.setArtifactType(artifact.getType()); + newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); + newEntry.setDescription(artifact.getDescription()); + + // Normalizing the artifact label to match those stored in DB + String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); + newEntry.setArtifactLabel(normalizeArtifactLabel); + newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); + newEntry.setArtifactChecksum(artifact.getChecksum()); + // Flag that set to true in case that the artifact is generated by AI&I generator + newEntry.setGenerated(Boolean.TRUE); + + artifactDefList.add(newEntry); + } + + return artifactDefList; + } + + // List> + // artifact stored by label + private List convertToGeneratorArtifactsInput(List> inputs) { + List listOfArtifactsInput = new LinkedList<>(); + for (ImmutablePair triple : inputs) { + Component component = triple.getLeft(); + + Map toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + String artifactName = artifactDefinition.getArtifactName(); + String artifactType = artifactDefinition.getArtifactType(); + String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); + String artifactDescription = artifactDefinition.getDescription(); + String artifactLabel = artifactDefinition.getArtifactLabel(); + byte[] right = triple.getRight(); + // The md5 calculated on the uncoded data + String md5Hex = DigestUtils.md5Hex(right); + byte[] payload = Base64.encodeBase64(right); + String artifactVersion = artifactDefinition.getArtifactVersion(); + + Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); + convertedArtifact.setName(artifactName); + convertedArtifact.setDescription(artifactDescription); + convertedArtifact.setLabel(artifactLabel); + convertedArtifact.setVersion(artifactVersion); + + listOfArtifactsInput.add(convertedArtifact); + } + + return listOfArtifactsInput; + } + + private Either getEntryData(String cassandraId, Component childComponent) { + byte[] content; + if (cassandraId == null || cassandraId.isEmpty()) { + Either exportRes = toscaExportUtils.exportComponent(childComponent); + if (exportRes.isRight()) { + log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); + return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); + } + content = exportRes.left().value().getMainYaml().getBytes(); + } else { + Either fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { + return Either.right(fromCassandra.right().value()); + } else { + content = fromCassandra.left().value(); + } + } + return Either.left(content); + } + + private Either getLatestSchemaFilesFromCassandra() { + Either, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); + + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); + } + + List listOfSchemas = specificSchemaFiles.left().value(); + + if(listOfSchemas.isEmpty()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); + } + + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + + return Either.left(schemaFile.getPayloadAsArray()); + } + + private Either getFromCassandra(String cassandraId) { + Either artifactResponse = artifactCassandraDao.getArtifact(cassandraId); + + if (artifactResponse.isRight()) { + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); + + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(convertedFromStorageResponse); + } + ESArtifactData artifactData = artifactResponse.left().value(); + return Either.left(artifactData.getDataAsArray()); + } + + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { + final String BLOCK_0_TEMPLATE = + "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; + String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); + return readyBlock; + } + + private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { + final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; + return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); + } + + private Either, String> artifactGenerator(List artifactList, ArtifactType type, Component component) { + + ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); + ArtifactTypes artifactTypes = new ArtifactTypes(); + List artifactTypesList = new LinkedList<>(); + ArtifactType otherType; + + if (type == null) { + otherType = ArtifactType.OTHER; + } else { + otherType = type; + } + + artifactTypesList.add(otherType); + artifactTypes.setArtifactTypes(artifactTypesList); + + String configJson = gson.toJson(artifactTypes); + Map additionalParams = new HashMap<>(); + String version; + + if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { + version = component.getVersion(); + } else { + String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; + } + + additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); + GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); + + Map> errorData = generatedArtifacts.getErrorData(); + + if (!errorData.isEmpty()) { + Set keySet = errorData.keySet(); + StringBuilder error = new StringBuilder(); + + for (String key : keySet) { + List errorList = errorData.get(key); + log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); + error.append(key + errorList); + } + + return Either.right(error.toString()); + } + + return Either.left(generatedArtifacts.getResultData()); + } + + /** + * Extracts artifacts of VFCs from CSAR + * + * @param csar + * @return Map of > the contains Lists of artifacts according vfcToscaNamespace + */ + public static Map> extractVfcsArtifactsFromCsar(Map csar) { + + Map> artifacts = new HashMap<>(); + if (csar != null) { + log.debug("************* Going to extract VFCs artifacts from Csar. "); + Map>> collectedWarningMessages = new HashMap<>(); + csar.entrySet().stream() + // filter CSAR entry by node type artifact path + .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path + .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); + // add counter suffix to artifact labels + handleWarningMessages(collectedWarningMessages); + + } + return artifacts; + } + + /** + * Print warnings to log + * + * @param collectedWarningMessages + */ + public static void handleWarningMessages(Map>> collectedWarningMessages) { + collectedWarningMessages.entrySet().stream() + // for each vfc + .forEach(e -> e.getValue().stream() + // add each warning message to log + .forEach(args -> log.warn(e.getKey(), args.toArray()))); + + } + + private static void addExtractedVfcArtifact(ImmutablePair extractedVfcArtifact, Map> artifacts) { + if (extractedVfcArtifact != null) { + List currArtifactsList; + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + if (artifacts.containsKey(vfcToscaNamespace)) { + currArtifactsList = artifacts.get(vfcToscaNamespace); + } else { + currArtifactsList = new ArrayList<>(); + artifacts.put(vfcToscaNamespace, currArtifactsList); + } + currArtifactsList.add(extractedVfcArtifact.getValue()); + } + } + + private static ImmutablePair extractVfcArtifact(Entry entry, Map>> collectedWarningMessages) { + ArtifactDefinition artifact; + String[] parsedCsarArtifactPath = entry.getKey().split("/"); + Either eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); + if (eitherArtifactGroupType.isLeft()) { + artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); + } else { + return null; + } + return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); + } + + private static Either detectArtifactGroupType(String groupType, Map>> collectedWarningMessages) { + Either result; + try { + ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); + if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { + String warningMessage = "Warning - unrecognized artifact group type {} was received."; + List messageArguments = new ArrayList<>(); + messageArguments.add(groupType); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + + result = Either.right(false); + } else { + + result = Either.left(artifactGroupType); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + result = Either.right(false); + } + return result; + } + + private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry entry, Map>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { + ArtifactDefinition artifact; + artifact = new ArtifactDefinition(); + artifact.setArtifactGroupType(artifactGroupType); + artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); + artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); + artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); + artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); + artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); + artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); + artifact.setIsFromCsar(true); + artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); + return artifact; + } + + public static final class NonMetaArtifactInfo { + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final ArtifactTypeEnum artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private String payloadData; + private String artifactChecksum; + private String artifactUniqueId; + private final boolean isFromCsar; + + public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) { + super(); + this.path = path; + this.isFromCsar = isFromCsar; + this.artifactName = ValidationUtils.normalizeFileName(artifactName); + this.artifactType = artifactType; + this.artifactGroupType = artifactGroupType; + final int pointIndex = artifactName.lastIndexOf('.'); + if (pointIndex > 0) { + displayName = artifactName.substring(0, pointIndex); + } else { + displayName = artifactName; + } + this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); + if (payloadData != null) { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + + public String getPath() { + return path; + } + + public String getArtifactName() { + return artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public String getDisplayName() { + return displayName; + } + + public ArtifactGroupTypeEnum getArtifactGroupType() { + return artifactGroupType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public boolean isFromCsar(){ + return isFromCsar; + } + + public String getPayloadData() { + return payloadData; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public String getArtifactUniqueId() { + return artifactUniqueId; + } + + public void setArtifactUniqueId(String artifactUniqueId) { + this.artifactUniqueId = artifactUniqueId; + } + + } + + /** + * This method checks the artifact GroupType & Artifact Type.
+ * if there is any problem warning messages are added to collectedWarningMessages + * + * @param artifactPath + * @param collectedWarningMessages + * @return + */ + public static Either validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map>> collectedWarningMessages) { + Either ret; + try { + String[] parsedArtifactPath = artifactPath.split("/"); + // Validate Artifact Group Type + Either eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); + if (eitherGroupType.isLeft()) { + final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); + + // Validate Artifact Type + String artifactType = parsedArtifactPath[2]; + artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); + + String artifactFileNameType = parsedArtifactPath[3]; + ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true)); + + } else { + ret = Either.right(eitherGroupType.right().value()); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + ret = Either.right(false); + } + return ret; + + } + + private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); + } + + private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); + } + + private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map>> collectedWarningMessages, String... arguments) { + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); + Map resourceValidTypeArtifacts = null; + + if(artifactGroupType != null){ + switch (artifactGroupType) { + case INFORMATIONAL: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceInformationalArtifacts(); + break; + case DEPLOYMENT: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceDeploymentArtifacts(); + break; + default: + break; + } + } + + Set validArtifactTypes = null; + if(resourceValidTypeArtifacts != null){ + validArtifactTypes = resourceValidTypeArtifacts.keySet(); + } + + if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { + List messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + + return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); + } + + private Either writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ + ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); + + Either writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + Map componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); + Set keySet = componentInstancesArtifacts.keySet(); + + String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; + for (String keyAssetName : keySet) { + ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); + String pathWithAssetName = currentPath + keyAssetName + "/"; + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + } + + return Either.left(zipstream); + } + + private Either writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, + String currentPath, boolean isInCertificationRequest) throws IOException { + Map componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); + //Keys are defined: + // folder name: _v. + //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" + Set componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); + for (String keyAssetName : componentTypeArtifactsKeys) { + ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); + ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); + String pathWithAssetName = currentPath + keyAssetName + "/"; + Either writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeArtifactsInfoToSpecifiedtPath.isRight()){ + return writeArtifactsInfoToSpecifiedtPath; + } + } + + return Either.left(zipstream); + } + + private Either writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { + Map>> artifactsInfo = currArtifactsInfo + .getArtifactsInfo(); + Set groupTypeEnumKeySet = artifactsInfo.keySet(); + + for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { + String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; + + Map> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); + Set artifactTypeEnumKeySet = artifactTypesMap.keySet(); + + for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { + List artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); + String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; + + Either writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); + + if(writeArtifactDefinition.isRight()){ + return writeArtifactDefinition; + } + } + } + + return Either.left(zip); + } + + private Either writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List artifactDefinitionList, + String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { + + ComponentTypeEnum componentType = mainComponent.getComponentType(); + String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); + + for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { + if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE + && artifactDefinition.getArtifactType().equals(heatEnvType) || //this is placeholder (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){ - continue; - } - - byte[] payloadData = artifactDefinition.getPayloadData(); - String artifactFileName = artifactDefinition.getArtifactName(); - - if (payloadData == null) { - Either fromCassandra = getFromCassandra(artifactDefinition.getEsId()); - - if (fromCassandra.isRight()) { + continue; + } + + byte[] payloadData = artifactDefinition.getPayloadData(); + String artifactFileName = artifactDefinition.getArtifactName(); + + if (payloadData == null) { + Either fromCassandra = getFromCassandra(artifactDefinition.getEsId()); + + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); - log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); - continue; - } - payloadData = fromCassandra.left().value(); - } - zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); - zip.write(payloadData); - } - - return Either.left(zip); - } - - /************************************ Artifacts Structure ******************************************************************/ - /** - * The artifacts Definition saved by their structure - */ - private class ArtifactsInfo { - //Key is the type of artifacts(Informational/Deployment) - //Value is a map between an artifact type and a list of all artifacts of this type - private Map>> artifactsInfoField; - - public ArtifactsInfo() { - this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); - } - - public Map>> getArtifactsInfo() { - return artifactsInfoField; - } - - public List getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ - List artifacts = new ArrayList<>(); - for (List artifactsByType:artifactsInfoField.get(artifactType).values()){ - artifacts.addAll(artifactsByType); - } - return artifacts; - } - - public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map> artifactsDefinition){ - artifactsInfoField.put(artifactGroup, artifactsDefinition); - } - - public boolean isEmpty() { - return artifactsInfoField.isEmpty(); - } - - } - - /** - * The artifacts of the component and of all its composed instances - * - */ - private class ComponentTypeArtifacts { - private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) - private Map componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) - - public ComponentTypeArtifacts() { - componentArtifacts = new ArtifactsInfo(); - componentInstancesArtifacts = new HashMap<>(); - } - - public ArtifactsInfo getComponentArtifacts() { - return componentArtifacts; - } - public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { - this.componentArtifacts = artifactsInfo; - } - public Map getComponentInstancesArtifacts() { - return componentInstancesArtifacts; - } - public void setComponentInstancesArtifacts(Map componentInstancesArtifacts) { - this.componentInstancesArtifacts = componentInstancesArtifacts; - } - - public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { - componentInstancesArtifacts.put(normalizedName, artifactsInfo); - } - - } - - private class ComponentArtifacts { - //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) - private ComponentTypeArtifacts mainTypeAndCIArtifacts; - //artifacts of all component types mapped by their tosca name - private Map componentTypeArtifacts; - - public ComponentArtifacts(){ - mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); - componentTypeArtifacts = new HashMap<>(); - } - - public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { - return mainTypeAndCIArtifacts; - } - - public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - this.mainTypeAndCIArtifacts = componentInstanceArtifacts; - } - - public Map getComponentTypeArtifacts() { - return componentTypeArtifacts; - } - - public void setComponentTypeArtifacts(Map componentTypeArtifacts) { - this.componentTypeArtifacts = componentTypeArtifacts; - } - } - - private class CsarDefinition { - private ComponentArtifacts componentArtifacts; - - // add list of tosca artifacts and meta describes CSAR zip root - - public CsarDefinition(ComponentArtifacts componentArtifacts) { - this.componentArtifacts = componentArtifacts; - } - - public ComponentArtifacts getComponentArtifacts() { - return componentArtifacts; - } - } - - /************************************ Artifacts Structure END******************************************************************/ - - private Either collectComponentCsarDefinition(Component component){ - ComponentArtifacts componentArtifacts = new ComponentArtifacts(); - Component updatedComponent = component; - - //get service to receive the AII artifacts uploaded to the service - if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { - Either getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); - - if(getServiceResponse.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - updatedComponent = getServiceResponse.left().value(); - } - - //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder - ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); - ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); - componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); - componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); - - Map resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) - //get the component instances - List componentInstances = updatedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance componentInstance:componentInstances){ - //call recursive to find artifacts for all the path - Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return Either.right(collectComponentInstanceArtifacts.right().value()); - } - } - } - - if(log.isDebugEnabled()){ - printResult(componentArtifacts,updatedComponent.getName()); - } - - return Either.left(new CsarDefinition(componentArtifacts)); - } - - private void printResult(ComponentArtifacts componentArtifacts, String name) { - StringBuilder result = new StringBuilder(); - result.append("Artifacts of main component " + name + "\n"); - ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - printArtifacts(componentInstanceArtifacts); - result.append("Type Artifacts\n"); - for (Map.Entry typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ - result.append("Folder " + typeArtifacts.getKey() + "\n"); - result.append(printArtifacts(typeArtifacts.getValue())); - } - - if(log.isDebugEnabled()){ - log.debug(result.toString()); - } - } - - private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - StringBuilder result = new StringBuilder(); - ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); - Map>> componetArtifacts = artifactsInfo.getArtifactsInfo(); - printArtifacts(componetArtifacts); - result = result.append("Resources\n"); - for (Map.Entry resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ - result.append("Folder" + resourceInstance.getKey() + "\n"); - result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); - } - - return result.toString(); - } - - private String printArtifacts(Map>> componetArtifacts) { - StringBuilder result = new StringBuilder(); - for (Map.Entry>> artifactGroup:componetArtifacts.entrySet()){ - result.append(" " + artifactGroup.getKey().getType()); - for (Map.Entry> groupArtifacts:artifactGroup.getValue().entrySet()){ - result.append(" " + groupArtifacts.getKey().getType()); - for (ArtifactDefinition artifact:groupArtifacts.getValue()){ - result.append(" " + artifact.getArtifactDisplayName()); - } - } - } - - return result.toString(); - } - - private ComponentTypeArtifacts collectComponentTypeArtifacts(Map resourcesArtifacts, ComponentInstance componentInstance, - Resource fetchedComponent) { - String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); - - ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); - //if there are no artifacts for this component type we need to fetch and build them - if (componentArtifactsInfo==null){ - ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); - componentArtifactsInfo = new ComponentTypeArtifacts(); - if (!componentArtifacts.isEmpty()){ - componentArtifactsInfo.setComponentArtifacts(componentArtifacts); - resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); - } - } - return componentArtifactsInfo; - } - - private Either collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, - Map resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { - //1. get the component instance component - String componentUid = componentInstance.getComponentUid(); - Either resource = toscaOperationFacade.getToscaElement(componentUid); - if (resource.isRight()) { - log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, - parentComponent.getComponentType().getValue(), parentComponent.getUUID(), - componentInstance.getOriginType().getComponentType().getValue(), componentUid)); - } - Resource fetchedComponent = resource.left().value(); - - //2. fill the artifacts for the current component parent type - ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); - - //3. find the artifacts specific to the instance - Map> componentInstanceSpecificInformationalArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); - Map> componentInstanceSpecificDeploymentArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); - - //4. add the instances artifacts to the component type - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); - } - if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); - } - if (!artifactsInfo.isEmpty()){ - instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); - } - - //5. do the same for all the component instances - List componentInstances = fetchedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance childComponentInstance:componentInstances){ - Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return collectComponentInstanceArtifacts; - } - } - } - - return Either.left(true); - } - - private Map> getComponentInstanceSpecificArtifacts(Map componentArtifacts, - Map>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { - Map> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance - - Map> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); - if (componentArtifacts!=null){ - for (ArtifactDefinition artifact:componentArtifacts.values()){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List parentArtifactsByType = null; - if (parentArtifacts!=null){ - parentArtifactsByType = parentArtifacts.get(artifactType); - } - //the artifact is of instance - if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ - List typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); - if (typeArtifacts == null){ - typeArtifacts = new ArrayList<>(); - artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - } - - return artifactsByTypeOfComponentInstance; - } - - private ArtifactsInfo collectComponentArtifacts(Component component) { - Map informationalArtifacts = component.getArtifacts(); - Map> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); - Map deploymentArtifacts = component.getDeploymentArtifacts(); - Map> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!informationalArtifactsByType.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); - } - if (!deploymentArtifactsByType.isEmpty() ){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); - } - - return artifactsInfo; - } - - private Map> collectGroupArtifacts(Map componentArtifacts) { - Map> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); - for (ArtifactDefinition artifact:componentArtifacts.values()){ - if (artifact.getArtifactUUID()!=null){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List typeArtifacts = artifactsByType.get(artifactType); - if (typeArtifacts==null){ - typeArtifacts = new ArrayList<>(); - artifactsByType.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - return artifactsByType; - } + log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); + continue; + } + payloadData = fromCassandra.left().value(); + } + zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); + zip.write(payloadData); + } + + return Either.left(zip); + } + + /************************************ Artifacts Structure ******************************************************************/ + /** + * The artifacts Definition saved by their structure + */ + private class ArtifactsInfo { + //Key is the type of artifacts(Informational/Deployment) + //Value is a map between an artifact type and a list of all artifacts of this type + private Map>> artifactsInfoField; + + public ArtifactsInfo() { + this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); + } + + public Map>> getArtifactsInfo() { + return artifactsInfoField; + } + + public List getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ + List artifacts = new ArrayList<>(); + for (List artifactsByType:artifactsInfoField.get(artifactType).values()){ + artifacts.addAll(artifactsByType); + } + return artifacts; + } + + public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map> artifactsDefinition){ + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + } + + /** + * The artifacts of the component and of all its composed instances + * + */ + private class ComponentTypeArtifacts { + private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) + private Map componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) + + public ComponentTypeArtifacts() { + componentArtifacts = new ArtifactsInfo(); + componentInstancesArtifacts = new HashMap<>(); + } + + public ArtifactsInfo getComponentArtifacts() { + return componentArtifacts; + } + public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { + this.componentArtifacts = artifactsInfo; + } + public Map getComponentInstancesArtifacts() { + return componentInstancesArtifacts; + } + public void setComponentInstancesArtifacts(Map componentInstancesArtifacts) { + this.componentInstancesArtifacts = componentInstancesArtifacts; + } + + public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { + componentInstancesArtifacts.put(normalizedName, artifactsInfo); + } + + } + + private class ComponentArtifacts { + //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) + private ComponentTypeArtifacts mainTypeAndCIArtifacts; + //artifacts of all component types mapped by their tosca name + private Map componentTypeArtifacts; + + public ComponentArtifacts(){ + mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); + componentTypeArtifacts = new HashMap<>(); + } + + public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { + return mainTypeAndCIArtifacts; + } + + public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + this.mainTypeAndCIArtifacts = componentInstanceArtifacts; + } + + public Map getComponentTypeArtifacts() { + return componentTypeArtifacts; + } + + public void setComponentTypeArtifacts(Map componentTypeArtifacts) { + this.componentTypeArtifacts = componentTypeArtifacts; + } + } + + private class CsarDefinition { + private ComponentArtifacts componentArtifacts; + + // add list of tosca artifacts and meta describes CSAR zip root + + public CsarDefinition(ComponentArtifacts componentArtifacts) { + this.componentArtifacts = componentArtifacts; + } + + public ComponentArtifacts getComponentArtifacts() { + return componentArtifacts; + } + } + + /************************************ Artifacts Structure END******************************************************************/ + + private Either collectComponentCsarDefinition(Component component){ + ComponentArtifacts componentArtifacts = new ComponentArtifacts(); + Component updatedComponent = component; + + //get service to receive the AII artifacts uploaded to the service + if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + Either getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); + + if(getServiceResponse.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + updatedComponent = getServiceResponse.left().value(); + } + + //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder + ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); + ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); + componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); + componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); + + Map resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) + //get the component instances + List componentInstances = updatedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance componentInstance:componentInstances){ + //call recursive to find artifacts for all the path + Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return Either.right(collectComponentInstanceArtifacts.right().value()); + } + } + } + + if(log.isDebugEnabled()){ + printResult(componentArtifacts,updatedComponent.getName()); + } + + return Either.left(new CsarDefinition(componentArtifacts)); + } + + private void printResult(ComponentArtifacts componentArtifacts, String name) { + StringBuilder result = new StringBuilder(); + result.append("Artifacts of main component " + name + "\n"); + ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + printArtifacts(componentInstanceArtifacts); + result.append("Type Artifacts\n"); + for (Map.Entry typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ + result.append("Folder " + typeArtifacts.getKey() + "\n"); + result.append(printArtifacts(typeArtifacts.getValue())); + } + + if(log.isDebugEnabled()){ + log.debug(result.toString()); + } + } + + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + StringBuilder result = new StringBuilder(); + ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); + Map>> componetArtifacts = artifactsInfo.getArtifactsInfo(); + printArtifacts(componetArtifacts); + result = result.append("Resources\n"); + for (Map.Entry resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ + result.append("Folder" + resourceInstance.getKey() + "\n"); + result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); + } + + return result.toString(); + } + + private String printArtifacts(Map>> componetArtifacts) { + StringBuilder result = new StringBuilder(); + for (Map.Entry>> artifactGroup:componetArtifacts.entrySet()){ + result.append(" " + artifactGroup.getKey().getType()); + for (Map.Entry> groupArtifacts:artifactGroup.getValue().entrySet()){ + result.append(" " + groupArtifacts.getKey().getType()); + for (ArtifactDefinition artifact:groupArtifacts.getValue()){ + result.append(" " + artifact.getArtifactDisplayName()); + } + } + } + + return result.toString(); + } + + private ComponentTypeArtifacts collectComponentTypeArtifacts(Map resourcesArtifacts, ComponentInstance componentInstance, + Resource fetchedComponent) { + String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); + + ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); + //if there are no artifacts for this component type we need to fetch and build them + if (componentArtifactsInfo==null){ + ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); + componentArtifactsInfo = new ComponentTypeArtifacts(); + if (!componentArtifacts.isEmpty()){ + componentArtifactsInfo.setComponentArtifacts(componentArtifacts); + resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); + } + } + return componentArtifactsInfo; + } + + private Either collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, + Map resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { + //1. get the component instance component + String componentUid = componentInstance.getComponentUid(); + Either resource = toscaOperationFacade.getToscaElement(componentUid); + if (resource.isRight()) { + log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); + } + Resource fetchedComponent = resource.left().value(); + + //2. fill the artifacts for the current component parent type + ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); + + //3. find the artifacts specific to the instance + Map> componentInstanceSpecificInformationalArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); + Map> componentInstanceSpecificDeploymentArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + + //4. add the instances artifacts to the component type + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); + } + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); + } + if (!artifactsInfo.isEmpty()){ + instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); + } + + //5. do the same for all the component instances + List componentInstances = fetchedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance childComponentInstance:componentInstances){ + Either collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return collectComponentInstanceArtifacts; + } + } + } + + return Either.left(true); + } + + private Map> getComponentInstanceSpecificArtifacts(Map componentArtifacts, + Map>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance + + Map> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); + if (componentArtifacts!=null){ + for (ArtifactDefinition artifact:componentArtifacts.values()){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List parentArtifactsByType = null; + if (parentArtifacts!=null){ + parentArtifactsByType = parentArtifacts.get(artifactType); + } + //the artifact is of instance + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ + List typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); + if (typeArtifacts == null){ + typeArtifacts = new ArrayList<>(); + artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + } + + return artifactsByTypeOfComponentInstance; + } + + private ArtifactsInfo collectComponentArtifacts(Component component) { + Map informationalArtifacts = component.getArtifacts(); + Map> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); + Map deploymentArtifacts = component.getDeploymentArtifacts(); + Map> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!informationalArtifactsByType.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); + } + if (!deploymentArtifactsByType.isEmpty() ){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); + } + + return artifactsInfo; + } + + private Map> collectGroupArtifacts(Map componentArtifacts) { + Map> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); + for (ArtifactDefinition artifact:componentArtifacts.values()){ + if (artifact.getArtifactUUID()!=null){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List typeArtifacts = artifactsByType.get(artifactType); + if (typeArtifacts==null){ + typeArtifacts = new ArrayList<>(); + artifactsByType.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + return artifactsByType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java index 083ea67769..f40ebf0e64 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java @@ -49,59 +49,59 @@ import com.google.gson.stream.JsonReader; import fj.data.Either; public class PropertyConvertor { - private static PropertyConvertor instance; - private JsonParser jsonParser = new JsonParser(); - private static Logger log = LoggerFactory.getLogger(PropertyConvertor.class.getName()); - Gson gson = new Gson(); - protected PropertyConvertor() { - - } - - public static synchronized PropertyConvertor getInstance() { - if (instance == null) { - instance = new PropertyConvertor(); - } - return instance; - } - - public Either convertProperties(Component component, ToscaNodeType toscaNodeType, Map dataTypes) { - - if (component instanceof Resource) { - Resource resource = (Resource) component; - List props = resource.getProperties(); - if (props != null) { - Map properties = new HashMap<>(); - - // take only the properties of this resource - props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { + private static PropertyConvertor instance; + private JsonParser jsonParser = new JsonParser(); + private static final Logger log = LoggerFactory.getLogger(PropertyConvertor.class); + Gson gson = new Gson(); + protected PropertyConvertor() { + + } + + public static synchronized PropertyConvertor getInstance() { + if (instance == null) { + instance = new PropertyConvertor(); + } + return instance; + } + + public Either convertProperties(Component component, ToscaNodeType toscaNodeType, Map dataTypes) { + + if (component instanceof Resource) { + Resource resource = (Resource) component; + List props = resource.getProperties(); + if (props != null) { + Map properties = new HashMap<>(); + + // take only the properties of this resource + props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { properties.put(property.getName(), convertProperty(dataTypes, property, false)); - }); - if (!properties.isEmpty()) { - toscaNodeType.setProperties(properties); - } - } - } - return Either.left(toscaNodeType); - } - - public ToscaProperty convertProperty(Map dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { - ToscaProperty prop = new ToscaProperty(); - - String innerType = null; - SchemaDefinition schema = property.getSchema(); - if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { - innerType = schema.getProperty().getType(); - EntrySchema eschema = new EntrySchema(); - eschema.setType(innerType); - eschema.setDescription(schema.getProperty().getDescription()); - prop.setEntry_schema(eschema); - } - log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); + }); + if (!properties.isEmpty()) { + toscaNodeType.setProperties(properties); + } + } + } + return Either.left(toscaNodeType); + } + + public ToscaProperty convertProperty(Map dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { + ToscaProperty prop = new ToscaProperty(); + + String innerType = null; + SchemaDefinition schema = property.getSchema(); + if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { + innerType = schema.getProperty().getType(); + EntrySchema eschema = new EntrySchema(); + eschema.setType(innerType); + eschema.setDescription(schema.getProperty().getDescription()); + prop.setEntry_schema(eschema); + } + log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); Object convertedObj = convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes); if (convertedObj != null) { prop.setDefaultp(convertedObj); } - prop.setType(property.getType()); + prop.setType(property.getType()); prop.setDescription(property.getDescription()); if (isCapabiltyProperty) { prop.setStatus(property.getStatus()); @@ -109,91 +109,91 @@ public class PropertyConvertor { } return prop; - } - - public Object convertToToscaObject(String propertyType, String value, String innerType, Map dataTypes) { - log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); - if (StringUtils.isEmpty(value)) { - value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); - if(StringUtils.isEmpty(value)){ - return null; - } - } - try { - ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); - ToscaValueConverter innerConverter = null; - Boolean isScalar = true; - - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - if (type == null) { - log.trace("isn't prederfined type, get from all data types"); - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (innerType == null) { - innerType = propertyType; - } - - if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { - log.trace("This is scalar type. get suitable converter for type {}", type); - innerConverter = type.getValueConverter(); - } else { - isScalar = false; - } - } else { - ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); - if (typeIfScalar == null) { - isScalar = false; - } - - innerConverter = type.getValueConverter(); - if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { - return innerConverter.convertToToscaValue(value, innerType, dataTypes); - } - } - JsonElement jsonElement = null; - - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - - jsonElement = jsonParser.parse(jsonReader); - - if (value.equals("")) { - return value; - } - - if (jsonElement.isJsonPrimitive() && isScalar) { - log.trace("It's well defined type. convert it"); - ToscaValueConverter converter = type.getValueConverter(); - return converter.convertToToscaValue(value, innerType, dataTypes); - } else { - log.trace("It's data type or inputs in primitive type. convert as map"); - Object convertedValue; - if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - if (isScalar) { - // complex json for scalar type - convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); - } else { - if (innerConverter != null) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); - } - } - } - return convertedValue; - } - - } catch (Exception e) { - log.debug("convertToToscaValue failed to parse json value :", e); - return null; - } - - } - - private boolean valueStartsWithNonJsonChar(String value) { - return value.startsWith("/") || value.startsWith(":"); - } + } + + public Object convertToToscaObject(String propertyType, String value, String innerType, Map dataTypes) { + log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); + if (StringUtils.isEmpty(value)) { + value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); + if(StringUtils.isEmpty(value)){ + return null; + } + } + try { + ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); + ToscaValueConverter innerConverter = null; + Boolean isScalar = true; + + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + if (type == null) { + log.trace("isn't prederfined type, get from all data types"); + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (innerType == null) { + innerType = propertyType; + } + + if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { + log.trace("This is scalar type. get suitable converter for type {}", type); + innerConverter = type.getValueConverter(); + } else { + isScalar = false; + } + } else { + ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); + if (typeIfScalar == null) { + isScalar = false; + } + + innerConverter = type.getValueConverter(); + if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { + return innerConverter.convertToToscaValue(value, innerType, dataTypes); + } + } + JsonElement jsonElement = null; + + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + + jsonElement = jsonParser.parse(jsonReader); + + if (value.equals("")) { + return value; + } + + if (jsonElement.isJsonPrimitive() && isScalar) { + log.trace("It's well defined type. convert it"); + ToscaValueConverter converter = type.getValueConverter(); + return converter.convertToToscaValue(value, innerType, dataTypes); + } else { + log.trace("It's data type or inputs in primitive type. convert as map"); + Object convertedValue; + if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + if (isScalar) { + // complex json for scalar type + convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); + } else { + if (innerConverter != null) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); + } + } + } + return convertedValue; + } + + } catch (Exception e) { + log.debug("convertToToscaValue failed to parse json value :", e); + return null; + } + + } + + private boolean valueStartsWithNonJsonChar(String value) { + return value.startsWith("/") || value.startsWith(":"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java index 94dd559d2d..c3acb43186 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.tosca; public enum ToscaError { - NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR + NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index c37c15f694..05be7f9cda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -20,19 +20,7 @@ package org.openecomp.sdc.be.tosca; -import java.beans.IntrospectionException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -44,42 +32,16 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; -import org.openecomp.sdc.be.tosca.model.IToscaMetadata; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaMetadata; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; -import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata; +import org.openecomp.sdc.be.tosca.model.*; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,1119 +59,1158 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import fj.data.Either; +import java.beans.IntrospectionException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-export-handler") public class ToscaExportHandler { - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - @Autowired - private CapabiltyRequirementConvertor capabiltyRequirementConvertor; - private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); - Map originComponents = new HashMap<>(); - - private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); - - public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; - public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; - public static final String IMPORTS_FILE_KEY = "file"; - public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; - public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; - public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; - public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; - public static final String VF_MODULE_DESC_KEY = "vf_module_description"; - public static final String VOLUME_GROUP_KEY = "volume_group"; - public static final String VF_MODULE_TYPE_BASE = "Base"; - public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; - private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; - private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; - protected static final List>> DEFAULT_IMPORTS = ConfigurationManager - .getConfigurationManager().getConfiguration().getDefaultImports(); - - public Either exportComponent(Component component) { - - Either toscaTemplateRes = convertToToscaTemplate(component); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public Either exportComponentInterface(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map nodeTypes = new HashMap<>(); - Either toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, - nodeTypes); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { - CustomRepresenter representer = new CustomRepresenter(); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(false); - options.setPrettyFlow(true); - - options.setDefaultFlowStyle(FlowStyle.FLOW); - options.setCanonical(false); - - representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); - - representer.setPropertyUtils(new UnsortedPropertyUtils()); - Yaml yaml = new Yaml(representer, options); - - String yamlAsString = yaml.dumpAsMap(toscaTemplate); - - StringBuilder sb = new StringBuilder(); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append(yamlAsString); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - - ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); - toscaRepresentation.setMainYaml(sb.toString()); - toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); - - return toscaRepresentation; - } - - public Either getDependencies(Component component) { - ToscaTemplate toscaTemplate = new ToscaTemplate(null); - Either>, ToscaError> fillImports = fillImports(component, - toscaTemplate); - if (fillImports.isRight()) { - return Either.right(fillImports.right().value()); - } - return Either.left(fillImports.left().value().left); - } - - private Either convertToToscaTemplate(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - log.trace("start tosca export for {}", component.getUniqueId()); - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - - toscaTemplate.setMetadata(convertMetadata(component)); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map nodeTypes = new HashMap<>(); - if (ModelConverter.isAtomicComponent(component)) { - log.trace("convert component as node type"); - return convertNodeType(component, toscaTemplate, nodeTypes); - } else { - log.trace("convert component as topology template"); - return convertToscaTemplate(component, toscaTemplate); - } - - } - - private Either convertToscaTemplate(Component component, ToscaTemplate toscaNode) { - - Either>, ToscaError> importsRes = fillImports(component, - toscaNode); - if (importsRes.isRight()) { - return Either.right(importsRes.right().value()); - } - toscaNode = importsRes.left().value().left; - Either, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component); - if (nodeTypesMapEither.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - nodeTypesMapEither.right().value()); - return Either.right(nodeTypesMapEither.right().value()); - } - Map nodeTypesMap = nodeTypesMapEither.left().value(); - if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) - toscaNode.setNode_types(nodeTypesMap); - - Map componentCache = importsRes.left().value().right; - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - Map dataTypes = dataTypesEither.left().value(); - - ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); - - Either inputs = fillInputs(component, topologyTemplate, dataTypes); - if (inputs.isRight()) { - return Either.right(inputs.right().value()); - } - topologyTemplate = inputs.left().value(); - - List componentInstances = component.getComponentInstances(); - Map> componentInstancesProperties = component - .getComponentInstancesProperties(); - List groups = component.getGroups(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - Either, ToscaError> nodeTemplates = convertNodeTemplates(component, - componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); - if (nodeTemplates.isRight()) { - return Either.right(nodeTemplates.right().value()); - } - log.debug("node templates converted"); - - topologyTemplate.setNode_templates(nodeTemplates.left().value()); - } - Map groupsMap; - if (groups != null && !groups.isEmpty()) { - groupsMap = new HashMap<>(); - for (GroupDefinition group : groups) { - boolean addToTosca = true; - if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - List artifacts = group.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - } - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroup(group); - groupsMap.put(group.getName(), toscaGroup); - } - - } - log.debug("groups converted"); - topologyTemplate.addGroups(groupsMap); - } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - substitutionMapping.setNode_type(toscaResourceName); - - Either capabilities = convertCapabilities(component, substitutionMapping); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - substitutionMapping = capabilities.left().value(); - - Either requirements = capabiltyRequirementConvertor - .convertSubstitutionMappingRequirements(originComponents, component, substitutionMapping); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - substitutionMapping = requirements.left().value(); - - topologyTemplate.setSubstitution_mappings(substitutionMapping); - - toscaNode.setTopology_template(topologyTemplate); - return Either.left(toscaNode); - } - - private Either fillInputs(Component component, - ToscaTopolgyTemplate topologyTemplate, Map dataTypes) { - if (log.isDebugEnabled()) - log.debug("fillInputs for component {}", component.getUniqueId()); - List inputDef = component.getInputs(); - Map inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - topologyTemplate.setInputs(inputs); - } - } - return Either.left(topologyTemplate); - } - - private ToscaMetadata convertMetadata(Component component) { - return convertMetadata(component, false, null); - } - - private ToscaMetadata convertMetadata(Component component, boolean isInstance, - ComponentInstance componentInstance) { - ToscaMetadata toscaMetadata = new ToscaMetadata(); - toscaMetadata.setInvariantUUID(component.getInvariantUUID()); - toscaMetadata.setUUID(component.getUUID()); - toscaMetadata.setDescription(component.getDescription()); - toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - List categories = component.getCategories(); - CategoryDefinition categoryDefinition = categories.get(0); - toscaMetadata.setCategory(categoryDefinition.getName()); - - if (isInstance) { - toscaMetadata.setVersion(component.getVersion()); - toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); - if (componentInstance.getSourceModelInvariant() != null - && !componentInstance.getSourceModelInvariant().isEmpty()) { - toscaMetadata.setVersion(componentInstance.getComponentVersion()); - toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); - toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); - toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); - toscaMetadata.setName( - componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); - toscaMetadata.setDescription(componentInstance.getDescription()); - } - - } - switch (component.getComponentType()) { - case RESOURCE: - Resource resource = (Resource) component; - - if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); - } else - toscaMetadata.setType(resource.getResourceType().name()); - toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); - toscaMetadata.setResourceVendor(resource.getVendorName()); - toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); - toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); - break; - case SERVICE: - Service service = (Service) component; - toscaMetadata.setType(component.getComponentType().getValue()); - toscaMetadata.setServiceType(service.getServiceType()); - toscaMetadata.setServiceRole(service.getServiceRole()); - toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); - if (!isInstance) { - // DE268546 - toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); - } - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - } - return toscaMetadata; - } - - private Either>, ToscaError> fillImports(Component component, - ToscaTemplate toscaTemplate) { - - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map componentCache = new HashMap<>(); - - if (!ModelConverter.isAtomicComponent(component)) { - List componentInstances = component.getComponentInstances(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - List>> additionalImports = toscaTemplate.getImports() == null - ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); - - List> dependecies = new ArrayList<>(); - - Map toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - Map> importsListMember = new HashMap<>(); - Map interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); - StringBuilder keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(component.getName()); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - additionalImports.add(importsListMember); - - componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); - originComponents.putAll(componentCache); - toscaTemplate.setDependencies(dependecies); - toscaTemplate.setImports(additionalImports); - } - } else { - log.debug("currently imports supported for VF and service only"); - } - return Either.left(new ImmutablePair>(toscaTemplate, componentCache)); - } - - private void createDependency(Map componentCache, List>> imports, - List> dependecies, ComponentInstance ci) { - Map files = new HashMap<>(); - Map> importsListMember = new HashMap<>(); - StringBuilder keyNameBuilder; - - Component componentRI = componentCache.get(ci.getComponentUid()); - if (componentRI == null) { - // all resource must be only once! - Either resource = toscaOperationFacade - .getToscaFullElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component fetchedComponent = resource.left().value(); - componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); - componentRI = fetchedComponent; - - Map toscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); - if (artifactDefinition != null) { - String artifactName = artifactDefinition.getArtifactName(); - files.put(IMPORTS_FILE_KEY, artifactName); - keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(ci.getComponentName()); - importsListMember.put(keyNameBuilder.toString(), files); - imports.add(importsListMember); - dependecies.add(new ImmutableTriple(artifactName, - artifactDefinition.getEsId(), fetchedComponent)); - - if (!ModelConverter.isAtomicComponent(componentRI)) { - importsListMember = new HashMap<>(); - Map interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - imports.add(importsListMember); - } - } - } - } - - public static String getInterfaceFilename(String artifactName) { - return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; - } - - private Either convertNodeType(Component component, ToscaTemplate toscaNode, - Map nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map dataTypes = dataTypesEither.left().value(); - Either properties = propertyConvertor.convertProperties(component, toscaNodeType, - dataTypes); - if (properties.isRight()) { - return Either.right(properties.right().value()); - } - toscaNodeType = properties.left().value(); - log.debug("Properties converted for {}", component.getUniqueId()); - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, - Map nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map dataTypes = dataTypesEither.left().value(); - - List inputDef = component.getInputs(); - Map inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - toscaNodeType.setProperties(inputs); - } - } - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, - Map nodeTypes, ToscaNodeType toscaNodeType, - Map dataTypes) { - Either capabilities = convertCapabilities(component, toscaNodeType, dataTypes); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - toscaNodeType = capabilities.left().value(); - log.debug("Capabilities converted for {}", component.getUniqueId()); - - Either requirements = capabiltyRequirementConvertor.convertRequirements(component, - toscaNodeType); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - toscaNodeType = requirements.left().value(); - log.debug("Requirements converted for {}", component.getUniqueId()); - - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - - nodeTypes.put(toscaResourceName, toscaNodeType); - toscaNode.setNode_types(nodeTypes); - log.debug("finish convert node type for {}", component.getUniqueId()); - return Either.left(toscaNode); - } - - private Either, ToscaError> convertNodeTemplates(Component component, - List componentInstances, - Map> componentInstancesProperties, - Map componentCache, Map dataTypes, - ToscaTopolgyTemplate topologyTemplate) { - - Either, ToscaError> convertNodeTemplatesRes = null; - log.debug("start convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - Map nodeTemplates = new HashMap<>(); - Map> componentInstancesInputs = component.getComponentInstancesInputs(); - - Map groupsMap = null; - for (ComponentInstance componentInstance : componentInstances) { - ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); - nodeTemplate.setType(componentInstance.getToscaComponentName()); - - Either originComponentRes = capabiltyRequirementConvertor - .getOriginComponent(componentCache, componentInstance); - if (originComponentRes.isRight()) { - convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - break; - } - Either requirements = convertComponentInstanceRequirements(component, - componentInstance, component.getComponentInstancesRelations(), nodeTemplate, - originComponentRes.left().value()); - if (requirements.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - String instanceUniqueId = componentInstance.getUniqueId(); - log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); - - nodeTemplate = requirements.left().value(); - - Component componentOfInstance = componentCache.get(componentInstance.getActualComponentUid()); - nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance)); - - Either capabilities = capabiltyRequirementConvertor - .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); - if (capabilities.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); - - nodeTemplate = capabilities.left().value(); - Map props = new HashMap<>(); - - if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) { - // Adds the properties of parent component to map - addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props); - } - - if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { - addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, - instanceUniqueId, props); - } - - if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { - addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, - props); - } - if (props != null && !props.isEmpty()) { - nodeTemplate.setProperties(props); - } - - List groupInstances = componentInstance.getGroupInstances(); - if (groupInstances != null) { - if (groupsMap == null) { - groupsMap = new HashMap<>(); - } - for (GroupInstance groupInst : groupInstances) { - boolean addToTosca = true; - - List artifacts = groupInst.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); - groupsMap.put(groupInst.getName(), toscaGroup); - } - } - } - - nodeTemplates.put(componentInstance.getName(), nodeTemplate); - } - if (groupsMap != null) { - log.debug("instance groups added"); - topologyTemplate.addGroups(groupsMap); - } - - if (convertNodeTemplatesRes == null) { - convertNodeTemplatesRes = Either.left(nodeTemplates); - } - log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - return convertNodeTemplatesRes; - } - - private void addComponentInstanceInputs(Map dataTypes, - Map> componentInstancesInputs, ComponentInstance componentInstance, - String instanceUniqueId, Map props) { - - List instanceInputsList = componentInstancesInputs.get(instanceUniqueId); - if (instanceInputsList != null) { - instanceInputsList.forEach(input -> { - - Supplier supplier = () -> input.getValue() != null && !input.getValue().isEmpty() - ? input.getValue() : input.getDefaultValue(); - convertAndAddValue(dataTypes, componentInstance, props, input, supplier); - }); - } - } - - private void addPropertiesOfComponentInstance( - Map> componentInstancesProperties, - Map dataTypes, ComponentInstance componentInstance, String instanceUniqueId, - Map props) { - - if (!MapUtils.isEmpty(componentInstancesProperties)) { - componentInstancesProperties.get(instanceUniqueId).stream() - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getValue())); - } - } - - private void addPropertiesOfParentComponent(Map dataTypes, - ComponentInstance componentInstance, Component componentOfInstance, Map props) { - - List componentProperties = ((Resource) componentOfInstance).getProperties(); - if (!CollectionUtils.isEmpty(componentProperties)) { - componentProperties.stream() - // Filters out properties with empty default values - .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getDefaultValue())); - } - } - - /** - * @param dataTypes - * @param componentInstance - * @param props - * @param prop - * @param supplier - */ - private void convertAndAddValue(Map dataTypes, ComponentInstance componentInstance, - Map props, PropertyDefinition prop, Supplier supplier) { - Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); - if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { - props.put(prop.getName(), convertedValue); - } - } - - private Object convertValue(Map dataTypes, - ComponentInstance componentInstance, T input, Supplier supplier) { - log.debug("Convert property or input value {} for instance {}", input.getName(), - componentInstance.getUniqueId()); - String propertyType = input.getType(); - String innerType = null; - if (input.getSchema() != null && input.getSchema().getProperty() != null) { - innerType = input.getSchema().getProperty().getType(); - } - return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); - } - - private ToscaGroupTemplate convertGroup(GroupDefinition group) { - - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - Map members = group.getMembers(); - if (members != null) - toscaGroup.setMembers(new ArrayList(members.keySet())); - - Supplier supplGroupType = () -> group.getType(); - Supplier supplDescription = () -> group.getDescription(); - Supplier> supplProperties = () -> group.convertToGroupProperties(); - Supplier supplgroupName = () -> group.getName(); - Supplier supplInvariantUUID = () -> group.getInvariantUUID(); - Supplier supplGroupUUID = () -> group.getGroupUUID(); - Supplier supplVersion = () -> group.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - - Supplier supplGroupType = () -> groupInstance.getType(); - Supplier supplDescription = () -> groupInstance.getDescription(); - Supplier> supplProperties = () -> groupInstance - .convertToGroupInstancesProperties(); - Supplier supplgroupName = () -> groupInstance.getGroupName(); - Supplier supplInvariantUUID = () -> groupInstance.getInvariantUUID(); - Supplier supplGroupUUID = () -> groupInstance.getGroupUUID(); - Supplier supplVersion = () -> groupInstance.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - - toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier> props, - Supplier description, Supplier groupName, Supplier invariantUUID, - Supplier groupUUID, Supplier version, Supplier groupType) { - boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; - toscaGroup.setType(groupType.get()); - - IToscaMetadata toscaMetadata; - if (!isVfModule) { - toscaMetadata = new ToscaMetadata(); - } else { - toscaMetadata = new VfModuleToscaMetadata(); - - Map properties = fillGroupProperties(props.get()); - if (!properties.containsKey(VF_MODULE_DESC_KEY) - || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { - properties.put(VF_MODULE_DESC_KEY, description.get()); - } - toscaGroup.setProperties(properties); - } - toscaMetadata.setName(groupName.get()); - toscaMetadata.setInvariantUUID(invariantUUID.get()); - toscaMetadata.setUUID(groupUUID.get()); - toscaMetadata.setVersion(version.get()); - return toscaMetadata; - } - - private Map fillGroupProperties(List groupProps) { - Map properties = new HashMap<>(); - if (groupProps != null) { - for (GroupProperty gp : groupProps) { - if (gp.getName().equals(Constants.IS_BASE)) { - Boolean isBase = Boolean.parseBoolean(gp.getValue()); - String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; - properties.put(VF_MODULE_TYPE_KEY, type); - } else { - Object value = null; - String type = gp.getType(); - - switch (type) { - case "integer": - if (gp.getValue() != null) { - value = Integer.valueOf(gp.getValue()); - } - break; - case "boolean": - if (gp.getValue() != null) { - value = Boolean.valueOf(gp.getValue()); - } - break; - - default: - value = gp.getValue(); - break; - } - properties.put(gp.getName(), value); - } - } - } - return properties; - } - - private ToscaNodeType createNodeType(Component component) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - if (ModelConverter.isAtomicComponent(component)) { - if (((Resource) component).getDerivedFrom() != null) { - toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); - } - toscaNodeType.setDescription(component.getDescription()); // or - // name?? - } else { - String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() - : "tosca.nodes.Root"; - toscaNodeType.setDerived_from(derivedFrom); - } - return toscaNodeType; - } - - private Either, ToscaError> createProxyNodeTypes(Component container) { - - Map nodeTypesMap = null; - Either, ToscaError> res = Either.left(nodeTypesMap); - - List componetInstances = container.getComponentInstances(); - - if (componetInstances == null || componetInstances.isEmpty()) - return res; - Map serviceProxyInstanceList = new HashMap<>(); - List proxyInst = componetInstances.stream() - .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) - .collect(Collectors.toList()); - if (proxyInst != null && !proxyInst.isEmpty()) { - for (ComponentInstance inst : proxyInst) { - serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); - } - } - - if (serviceProxyInstanceList.isEmpty()) - return res; - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreComponentInstances(false); - Either serviceProxyOrigin = toscaOperationFacade - .getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - serviceProxyOrigin.right().value()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - Component origComponent = serviceProxyOrigin.left().value(); - - nodeTypesMap = new HashMap<>(); - for (Entry entryProxy : serviceProxyInstanceList.entrySet()) { - Component serviceComponent = null; - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - Either service = toscaOperationFacade - .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); - if (service.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } else - serviceComponent = service.left().value(); - - ToscaNodeType toscaNodeType = createProxyNodeType(origComponent, serviceComponent, entryProxy.getValue()); - nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); - } - - return Either.left(nodeTypesMap); - } - - private ToscaNodeType createProxyNodeType(Component origComponent, Component proxyComponent, - ComponentInstance instance) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - String derivedFrom = ((Resource) origComponent).getToscaResourceName(); - - toscaNodeType.setDerived_from(derivedFrom); - Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - } - Map dataTypes = dataTypesEither.left().value(); - Map capabilities = this.capabiltyRequirementConvertor - .convertProxyCapabilities(origComponent, proxyComponent, instance, dataTypes); - - toscaNodeType.setCapabilities(capabilities); - - return toscaNodeType; - } - - private Either convertComponentInstanceRequirements(Component component, - ComponentInstance componentInstance, List relations, - ToscaNodeTemplate nodeTypeTemplate, Component originComponent) { - - List> toscaRequirements = new ArrayList<>(); - if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)) { - log.debug("Failed to convert component instance requirements for the component instance {}. ", - componentInstance.getName()); - return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - if (!toscaRequirements.isEmpty()) { - nodeTypeTemplate.setRequirements(toscaRequirements); - } - log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); - return Either.left(nodeTypeTemplate); - } - - private boolean addRequirements(Component component, ComponentInstance componentInstance, - List relations, Component originComponent, - List> toscaRequirements) { - boolean result; - List filteredRelations = relations.stream() - .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(filteredRelations)) { - result = true; - } else { - result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, - component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent(); - } - return result; - } - - private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, - List instancesList, RequirementCapabilityRelDef rel, - List> toscaRequirements) { - - boolean result = true; - Map> reqMap = fromOriginComponent.getRequirements(); - RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); - Either getOriginRes = null; - Optional reqOpt = null; - Component toOriginComponent = null; - Optional cap = null; - - ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) - .findFirst().orElse(null); - if (toInstance == null) { - log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), - rel.getToNode()); - result = false; - } - if (result) { - reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, toInstance.getUniqueId()); - if (!reqOpt.isPresent()) { - log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - filter.setIgnoreCapabilities(false); - getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); - if (getOriginRes.isRight()) { - log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", - reqOpt.get().getName(), toInstance.getActualComponentUid()); - result = false; - } - } - if (result) { - toOriginComponent = getOriginRes.left().value(); - cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() - .filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst(); - if (!cap.isPresent()) { - cap = findCapability(reqMap, reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); - if(!cap.isPresent()){ - result = false; - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - } - if (result) { - result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), - reqOpt.get(), reqAndRelationshipPair, toInstance); - } - return result; - } - - private Optional findCapability(Map> reqMap, RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { - Optional cap = Optional.empty(); - Optional findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny(); - if (findAny.isPresent()) { - RequirementDefinition reqDefinition = findAny.get(); - cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(reqDefinition.getCapability())).findFirst(); - if (!cap.isPresent()) { - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - return cap; - } - - private boolean buildAndAddRequirement(List> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance) { - boolean result = true; - Either buildReqNameRes = null; - Either buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, - toOriginComponent, capability.getPath(), reqAndRelationshipPair.getCapability()); - if (buildCapNameRes.isRight()) { - log.debug( - "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - result = false; - } - if (result) { - buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, fromOriginComponent, - requirement.getPath(), reqAndRelationshipPair.getRequirement()); - if (buildReqNameRes.isRight()) { - log.debug( - "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); - Map toscaReqMap = new HashMap<>(); - toscaRequirement.setNode(toInstance.getName()); - toscaRequirement.setCapability(buildCapNameRes.left().value()); - toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); - toscaRequirements.add(toscaReqMap); - } - return result; - } - - private Optional findRequirement(Component fromOriginComponent, Map> reqMap, RelationshipInfo reqAndRelationshipPair, String toInstanceId) { - for(List reqList: reqMap.values()){ - Optional reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, toInstanceId)).findFirst(); - if(reqOpt.isPresent()){ - return reqOpt; - } - } - return Optional.empty(); - } - - /** - * Allows detecting the requirement belonging to the received relationship - * The detection logic is: A requirement belongs to a relationship IF 1.The - * name of the requirement equals to the "requirement" field of the - * relation; AND 2. In case of a non-atomic resource, OwnerId of the - * requirement equals to requirementOwnerId of the relation OR uniqueId of - * toInstance equals to capabilityOwnerId of the relation - * - * @param fromOriginComponent - * @param reqAndRelationshipPair - * @param requirement - * @param toInstanceId - * @return - */ - private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) - return false; - if (!ModelConverter.isAtomicComponent(originComponent)) - return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, toInstanceId); - return true; - } - - private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils.equals(toInstanceId, reqAndRelationshipPair.getCapabilityOwnerId()); - } - - private Either convertCapabilities(Component component, - SubstitutionMapping substitutionMappings) { - - Either result = Either.left(substitutionMappings); - Either, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor - .convertSubstitutionMappingCapabilities(originComponents, component); - if (toscaCapabilitiesRes.isRight()) { - result = Either.right(toscaCapabilitiesRes.right().value()); - log.error("Failed convert capabilities for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { - substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); - log.debug("Finish convert capabilities for the component {}. ", component.getName()); - } - log.debug("Finished to convert capabilities for the component {}. ", component.getName()); - return result; - } - - private Either convertCapabilities(Component component, ToscaNodeType nodeType, - Map dataTypes) { - Map toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, - dataTypes); - if (!toscaCapabilities.isEmpty()) { - nodeType.setCapabilities(toscaCapabilities); - } - log.debug("Finish convert Capabilities for node type"); - - return Either.left(nodeType); - } - - private static class CustomRepresenter extends Representer { - public CustomRepresenter() { - super(); - // null representer is exceptional and it is stored as an instance - // variable. - this.nullRepresenter = new RepresentNull(); - - } - - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, - Tag customTag) { - if (propertyValue == null) { - return null; - } else { - // skip not relevant for Tosca property - if ("dependencies".equals(property.getName())) { - return null; - } - NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - - return "_defaultp_".equals(property.getName()) - ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; - } - } - - @Override - protected MappingNode representJavaBean(Set properties, Object javaBean) { - // remove the bean type from the output yaml (!! ...) - if (!classTags.containsKey(javaBean.getClass())) - addClassTag(javaBean.getClass(), Tag.MAP); - - return super.representJavaBean(properties, javaBean); - } - - private class RepresentNull implements Represent { - @Override - public Node representData(Object data) { - // possible values are here http://yaml.org/type/null.html - return representScalar(Tag.NULL, ""); - } - } - } - - private static class UnsortedPropertyUtils extends PropertyUtils { - @Override - protected Set createPropertySet(Class type, BeanAccess bAccess) - throws IntrospectionException { - Collection fields = getPropertiesMap(type, BeanAccess.FIELD).values(); - return new LinkedHashSet<>(fields); - } - } + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private CapabiltyRequirementConvertor capabiltyRequirementConvertor; + private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); + + private static final Logger log = LoggerFactory.getLogger(ToscaExportHandler.class); + + public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; + public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; + public static final String IMPORTS_FILE_KEY = "file"; + public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; + public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; + public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; + public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; + public static final String VF_MODULE_DESC_KEY = "vf_module_description"; + public static final String VOLUME_GROUP_KEY = "volume_group"; + public static final String VF_MODULE_TYPE_BASE = "Base"; + public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; + private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; + private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; + protected static final List>> DEFAULT_IMPORTS = ConfigurationManager + .getConfigurationManager().getConfiguration().getDefaultImports(); + + public Either exportComponent(Component component) { + + Either toscaTemplateRes = convertToToscaTemplate(component); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public Either exportComponentInterface(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map nodeTypes = new HashMap<>(); + Either toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, + nodeTypes); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { + CustomRepresenter representer = new CustomRepresenter(); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(false); + options.setPrettyFlow(true); + + options.setDefaultFlowStyle(FlowStyle.FLOW); + options.setCanonical(false); + + representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); + + representer.setPropertyUtils(new UnsortedPropertyUtils()); + Yaml yaml = new Yaml(representer, options); + + String yamlAsString = yaml.dumpAsMap(toscaTemplate); + + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append(yamlAsString); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + + ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); + toscaRepresentation.setMainYaml(sb.toString()); + toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); + + return toscaRepresentation; + } + + public Either getDependencies(Component component) { + ToscaTemplate toscaTemplate = new ToscaTemplate(null); + Either>, ToscaError> fillImports = fillImports(component, + toscaTemplate); + if (fillImports.isRight()) { + return Either.right(fillImports.right().value()); + } + return Either.left(fillImports.left().value().left); + } + + private Either convertToToscaTemplate(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + log.trace("start tosca export for {}", component.getUniqueId()); + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + + toscaTemplate.setMetadata(convertMetadata(component)); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map nodeTypes = new HashMap<>(); + if (ModelConverter.isAtomicComponent(component)) { + log.trace("convert component as node type"); + return convertNodeType(component, toscaTemplate, nodeTypes); + } else { + log.trace("convert component as topology template"); + return convertToscaTemplate(component, toscaTemplate); + } + + } + + private Either convertToscaTemplate(Component component, ToscaTemplate toscaNode) { + + Either>, ToscaError> importsRes = fillImports(component, + toscaNode); + if (importsRes.isRight()) { + return Either.right(importsRes.right().value()); + } + toscaNode = importsRes.left().value().left; + Map componentCache = importsRes.left().value().right; + Either, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component ); + if (nodeTypesMapEither.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + nodeTypesMapEither.right().value()); + return Either.right(nodeTypesMapEither.right().value()); + } + Map nodeTypesMap = nodeTypesMapEither.left().value(); + if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) + toscaNode.setNode_types(nodeTypesMap); + + + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map dataTypes = dataTypesEither.left().value(); + + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + + Either inputs = fillInputs(component, topologyTemplate, dataTypes); + if (inputs.isRight()) { + return Either.right(inputs.right().value()); + } + topologyTemplate = inputs.left().value(); + + List componentInstances = component.getComponentInstances(); + Map> componentInstancesProperties = component + .getComponentInstancesProperties(); + List groups = component.getGroups(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + Either, ToscaError> nodeTemplates = convertNodeTemplates(component, + componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + if (nodeTemplates.isRight()) { + return Either.right(nodeTemplates.right().value()); + } + log.debug("node templates converted"); + + topologyTemplate.setNode_templates(nodeTemplates.left().value()); + } + Map groupsMap; + if (groups != null && !groups.isEmpty()) { + groupsMap = new HashMap<>(); + for (GroupDefinition group : groups) { + boolean addToTosca = true; + if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + List artifacts = group.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + } + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroup(group); + groupsMap.put(group.getName(), toscaGroup); + } + + } + log.debug("groups converted"); + topologyTemplate.addGroups(groupsMap); + } + SubstitutionMapping substitutionMapping = new SubstitutionMapping(); + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + substitutionMapping.setNode_type(toscaResourceName); + + Either capabilities = convertCapabilities(component, substitutionMapping, componentCache); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + substitutionMapping = capabilities.left().value(); + + Either requirements = capabiltyRequirementConvertor + .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + substitutionMapping = requirements.left().value(); + + topologyTemplate.setSubstitution_mappings(substitutionMapping); + + toscaNode.setTopology_template(topologyTemplate); + return Either.left(toscaNode); + } + + private Either fillInputs(Component component, + ToscaTopolgyTemplate topologyTemplate, Map dataTypes) { + if (log.isDebugEnabled()) + log.debug("fillInputs for component {}", component.getUniqueId()); + List inputDef = component.getInputs(); + Map inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + topologyTemplate.setInputs(inputs); + } + } + return Either.left(topologyTemplate); + } + + private ToscaMetadata convertMetadata(Component component) { + return convertMetadata(component, false, null); + } + + private ToscaMetadata convertMetadata(Component component, boolean isInstance, + ComponentInstance componentInstance) { + ToscaMetadata toscaMetadata = new ToscaMetadata(); + toscaMetadata.setInvariantUUID(component.getInvariantUUID()); + toscaMetadata.setUUID(component.getUUID()); + toscaMetadata.setDescription(component.getDescription()); + toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + List categories = component.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + toscaMetadata.setCategory(categoryDefinition.getName()); + + if (isInstance) { + toscaMetadata.setVersion(component.getVersion()); + toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); + if (componentInstance.getSourceModelInvariant() != null + && !componentInstance.getSourceModelInvariant().isEmpty()) { + toscaMetadata.setVersion(componentInstance.getComponentVersion()); + toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); + toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); + toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); + toscaMetadata.setName( + componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); + toscaMetadata.setDescription(componentInstance.getDescription()); + } + + } + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource) component; + + if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); + } else + toscaMetadata.setType(resource.getResourceType().name()); + toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); + toscaMetadata.setResourceVendor(resource.getVendorName()); + toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); + toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); + break; + case SERVICE: + Service service = (Service) component; + toscaMetadata.setType(component.getComponentType().getValue()); + toscaMetadata.setServiceType(service.getServiceType()); + toscaMetadata.setServiceRole(service.getServiceRole()); + toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); + if (!isInstance) { + // DE268546 + toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); + } + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + } + return toscaMetadata; + } + + private Either>, ToscaError> fillImports(Component component, + ToscaTemplate toscaTemplate) { + + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map componentCache = new HashMap<>(); + + if (!ModelConverter.isAtomicComponent(component)) { + List componentInstances = component.getComponentInstances(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + List>> additionalImports = toscaTemplate.getImports() == null + ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); + + List> dependecies = new ArrayList<>(); + + Map toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + Map> importsListMember = new HashMap<>(); + Map interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); + StringBuilder keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(component.getName()); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + additionalImports.add(importsListMember); + + componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); + toscaTemplate.setDependencies(dependecies); + toscaTemplate.setImports(additionalImports); + } + } else { + log.debug("currently imports supported for VF and service only"); + } + return Either.left(new ImmutablePair>(toscaTemplate, componentCache)); + } + + private void createDependency(Map componentCache, List>> imports, + List> dependecies, ComponentInstance ci) { + Map files = new HashMap<>(); + Map> importsListMember = new HashMap<>(); + StringBuilder keyNameBuilder; + + Component componentRI = componentCache.get(ci.getComponentUid()); + if (componentRI == null) { + // all resource must be only once! + Either resource = toscaOperationFacade + .getToscaFullElement(ci.getComponentUid()); + if ((resource.isRight()) && (log.isDebugEnabled())) { + log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + return ; + } + + Component fetchedComponent = resource.left().value(); + componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); + + if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){ + Either sourceService = toscaOperationFacade + .getToscaFullElement(ci.getSourceModelUid()); + if (sourceService.isRight() && (log.isDebugEnabled())) { + log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId()); + } + Component fetchedSource = sourceService.left().value(); + componentCache.put(fetchedSource.getUniqueId(), fetchedSource); + } + + componentRI = fetchedComponent; + + Map toscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); + if (artifactDefinition != null) { + String artifactName = artifactDefinition.getArtifactName(); + files.put(IMPORTS_FILE_KEY, artifactName); + keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(ci.getComponentName()); + importsListMember.put(keyNameBuilder.toString(), files); + imports.add(importsListMember); + dependecies.add(new ImmutableTriple(artifactName, + artifactDefinition.getEsId(), fetchedComponent)); + + if (!ModelConverter.isAtomicComponent(componentRI)) { + importsListMember = new HashMap<>(); + Map interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + imports.add(importsListMember); + } + } + } + } + + public static String getInterfaceFilename(String artifactName) { + return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + } + + private Either convertNodeType(Component component, ToscaTemplate toscaNode, + Map nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map dataTypes = dataTypesEither.left().value(); + Either properties = propertyConvertor.convertProperties(component, toscaNodeType, + dataTypes); + if (properties.isRight()) { + return Either.right(properties.right().value()); + } + toscaNodeType = properties.left().value(); + log.debug("Properties converted for {}", component.getUniqueId()); + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, + Map nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map dataTypes = dataTypesEither.left().value(); + + List inputDef = component.getInputs(); + Map inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + toscaNodeType.setProperties(inputs); + } + } + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, + Map nodeTypes, ToscaNodeType toscaNodeType, + Map dataTypes) { + Either capabilities = convertCapabilities(component, toscaNodeType, dataTypes); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + toscaNodeType = capabilities.left().value(); + log.debug("Capabilities converted for {}", component.getUniqueId()); + + Either requirements = capabiltyRequirementConvertor.convertRequirements(component, + toscaNodeType); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + toscaNodeType = requirements.left().value(); + log.debug("Requirements converted for {}", component.getUniqueId()); + + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + + nodeTypes.put(toscaResourceName, toscaNodeType); + toscaNode.setNode_types(nodeTypes); + log.debug("finish convert node type for {}", component.getUniqueId()); + return Either.left(toscaNode); + } + + private Either, ToscaError> convertNodeTemplates(Component component, + List componentInstances, + Map> componentInstancesProperties, + Map componentCache, Map dataTypes, + ToscaTopolgyTemplate topologyTemplate) { + + Either, ToscaError> convertNodeTemplatesRes = null; + log.debug("start convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + Map nodeTemplates = new HashMap<>(); + Map> componentInstancesInputs = component.getComponentInstancesInputs(); + + Map groupsMap = null; + for (ComponentInstance componentInstance : componentInstances) { + ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); + nodeTemplate.setType(componentInstance.getToscaComponentName()); + + Either originComponentRes = capabiltyRequirementConvertor + .getOriginComponent(componentCache, componentInstance); + if (originComponentRes.isRight()) { + convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + break; + } + Either requirements = convertComponentInstanceRequirements(component, + componentInstance, component.getComponentInstancesRelations(), nodeTemplate, + originComponentRes.left().value(), componentCache); + if (requirements.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + String instanceUniqueId = componentInstance.getUniqueId(); + log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); + + nodeTemplate = requirements.left().value(); + + Component originalComponent = componentCache.get(componentInstance.getActualComponentUid()); + + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){ + Component componentOfProxy = componentCache.get(componentInstance.getComponentUid()); + nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance)); + } else { + nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance)); + } + + Either capabilities = capabiltyRequirementConvertor + .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); + if (capabilities.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); + + nodeTemplate = capabilities.left().value(); + Map props = new HashMap<>(); + + if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) { + // Adds the properties of parent component to map + addPropertiesOfParentComponent(dataTypes, componentInstance, originalComponent, props); + } + + if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { + addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, + instanceUniqueId, props); + } + + if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { + addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, + props); + } + if (props != null && !props.isEmpty()) { + nodeTemplate.setProperties(props); + } + + List groupInstances = componentInstance.getGroupInstances(); + if (groupInstances != null) { + if (groupsMap == null) { + groupsMap = new HashMap<>(); + } + for (GroupInstance groupInst : groupInstances) { + boolean addToTosca = true; + + List artifacts = groupInst.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + groupsMap.put(groupInst.getName(), toscaGroup); + } + } + } + + nodeTemplates.put(componentInstance.getName(), nodeTemplate); + } + if (groupsMap != null) { + log.debug("instance groups added"); + topologyTemplate.addGroups(groupsMap); + } + if (component.getComponentType() == ComponentTypeEnum.SERVICE && MapUtils.isNotEmpty(((Service) component).getForwardingPaths())) { + log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabiltyRequirementConvertor, componentCache, toscaOperationFacade); + log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + } + if (convertNodeTemplatesRes == null) { + convertNodeTemplatesRes = Either.left(nodeTemplates); + } + log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + return convertNodeTemplatesRes; + } + + private void addComponentInstanceInputs(Map dataTypes, + Map> componentInstancesInputs, ComponentInstance componentInstance, + String instanceUniqueId, Map props) { + + List instanceInputsList = componentInstancesInputs.get(instanceUniqueId); + if (instanceInputsList != null) { + instanceInputsList.forEach(input -> { + + Supplier supplier = () -> input.getValue() != null && !input.getValue().isEmpty() + ? input.getValue() : input.getDefaultValue(); + convertAndAddValue(dataTypes, componentInstance, props, input, supplier); + }); + } + } + + private void addPropertiesOfComponentInstance( + Map> componentInstancesProperties, + Map dataTypes, ComponentInstance componentInstance, String instanceUniqueId, + Map props) { + + if (!MapUtils.isEmpty(componentInstancesProperties)) { + componentInstancesProperties.get(instanceUniqueId).stream() + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getValue())); + } + } + + private void addPropertiesOfParentComponent(Map dataTypes, + ComponentInstance componentInstance, Component componentOfInstance, Map props) { + + List componentProperties = ((Resource) componentOfInstance).getProperties(); + if (!CollectionUtils.isEmpty(componentProperties)) { + componentProperties.stream() + // Filters out properties with empty default values + .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getDefaultValue())); + } + } + + /** + * @param dataTypes + * @param componentInstance + * @param props + * @param prop + * @param supplier + */ + private void convertAndAddValue(Map dataTypes, ComponentInstance componentInstance, + Map props, PropertyDefinition prop, Supplier supplier) { + Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); + if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { + props.put(prop.getName(), convertedValue); + } + } + + private Object convertValue(Map dataTypes, + ComponentInstance componentInstance, T input, Supplier supplier) { + log.debug("Convert property or input value {} for instance {}", input.getName(), + componentInstance.getUniqueId()); + String propertyType = input.getType(); + String innerType = null; + if (input.getSchema() != null && input.getSchema().getProperty() != null) { + innerType = input.getSchema().getProperty().getType(); + } + return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); + } + + private ToscaGroupTemplate convertGroup(GroupDefinition group) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + Map members = group.getMembers(); + if (members != null) + toscaGroup.setMembers(new ArrayList(members.keySet())); + + Supplier supplGroupType = () -> group.getType(); + Supplier supplDescription = () -> group.getDescription(); + Supplier> supplProperties = () -> group.convertToGroupProperties(); + Supplier supplgroupName = () -> group.getName(); + Supplier supplInvariantUUID = () -> group.getInvariantUUID(); + Supplier supplGroupUUID = () -> group.getGroupUUID(); + Supplier supplVersion = () -> group.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + + Supplier supplGroupType = () -> groupInstance.getType(); + Supplier supplDescription = () -> groupInstance.getDescription(); + Supplier> supplProperties = () -> groupInstance + .convertToGroupInstancesProperties(); + Supplier supplgroupName = () -> groupInstance.getGroupName(); + Supplier supplInvariantUUID = () -> groupInstance.getInvariantUUID(); + Supplier supplGroupUUID = () -> groupInstance.getGroupUUID(); + Supplier supplVersion = () -> groupInstance.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + + toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier> props, + Supplier description, Supplier groupName, Supplier invariantUUID, + Supplier groupUUID, Supplier version, Supplier groupType) { + boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; + toscaGroup.setType(groupType.get()); + + IToscaMetadata toscaMetadata; + if (!isVfModule) { + toscaMetadata = new ToscaMetadata(); + } else { + toscaMetadata = new VfModuleToscaMetadata(); + + Map properties = fillGroupProperties(props.get()); + if (!properties.containsKey(VF_MODULE_DESC_KEY) + || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { + properties.put(VF_MODULE_DESC_KEY, description.get()); + } + toscaGroup.setProperties(properties); + } + toscaMetadata.setName(groupName.get()); + toscaMetadata.setInvariantUUID(invariantUUID.get()); + toscaMetadata.setUUID(groupUUID.get()); + toscaMetadata.setVersion(version.get()); + return toscaMetadata; + } + + private Map fillGroupProperties(List groupProps) { + Map properties = new HashMap<>(); + if (groupProps != null) { + for (GroupProperty gp : groupProps) { + if (gp.getName().equals(Constants.IS_BASE)) { + Boolean isBase = Boolean.parseBoolean(gp.getValue()); + String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; + properties.put(VF_MODULE_TYPE_KEY, type); + } else { + Object value = null; + String type = gp.getType(); + + switch (type) { + case "integer": + if (gp.getValue() != null) { + value = Integer.valueOf(gp.getValue()); + } + break; + case "boolean": + if (gp.getValue() != null) { + value = Boolean.valueOf(gp.getValue()); + } + break; + + default: + value = gp.getValue(); + break; + } + properties.put(gp.getName(), value); + } + } + } + return properties; + } + + private ToscaNodeType createNodeType(Component component) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + if (ModelConverter.isAtomicComponent(component)) { + if (((Resource) component).getDerivedFrom() != null) { + toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); + } + toscaNodeType.setDescription(component.getDescription()); // or + // name?? + } else { + String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() + : "tosca.nodes.Root"; + toscaNodeType.setDerived_from(derivedFrom); + } + return toscaNodeType; + } + + private Either, ToscaError> createProxyNodeTypes(Map componentCache ,Component container ) { + + Map nodeTypesMap = null; + Either, ToscaError> res = Either.left(nodeTypesMap); + + List componetInstances = container.getComponentInstances(); + + if (componetInstances == null || componetInstances.isEmpty()) + return res; + Map serviceProxyInstanceList = new HashMap<>(); + List proxyInst = componetInstances.stream() + .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) + .collect(Collectors.toList()); + if (proxyInst != null && !proxyInst.isEmpty()) { + for (ComponentInstance inst : proxyInst) { + serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); + } + } + + if (serviceProxyInstanceList.isEmpty()) + return res; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreComponentInstances(false); + Either serviceProxyOrigin = toscaOperationFacade + .getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + serviceProxyOrigin.right().value()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + Component origComponent = serviceProxyOrigin.left().value(); + + nodeTypesMap = new HashMap<>(); + for (Entry entryProxy : serviceProxyInstanceList.entrySet()) { + Component serviceComponent = null; + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + Either service = toscaOperationFacade + .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); + if (service.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } else + serviceComponent = service.left().value(); + + ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue()); + nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); + } + + return Either.left(nodeTypesMap); + } + + private ToscaNodeType createProxyNodeType(Map componentCache , Component origComponent, Component proxyComponent, + ComponentInstance instance) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + String derivedFrom = ((Resource) origComponent).getToscaResourceName(); + + toscaNodeType.setDerived_from(derivedFrom); + Either, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + } + Map dataTypes = dataTypesEither.left().value(); + Map capabilities = this.capabiltyRequirementConvertor + .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes); + + toscaNodeType.setCapabilities(capabilities); + + return toscaNodeType; + } + + private Either convertComponentInstanceRequirements(Component component, + ComponentInstance componentInstance, List relations, + ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map componentCache) { + + List> toscaRequirements = new ArrayList<>(); + if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) { + log.debug("Failed to convert component instance requirements for the component instance {}. ", + componentInstance.getName()); + return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + if (!toscaRequirements.isEmpty()) { + nodeTypeTemplate.setRequirements(toscaRequirements); + } + log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); + return Either.left(nodeTypeTemplate); + } + + private boolean addRequirements(Component component, ComponentInstance componentInstance, + List relations, Component originComponent, + List> toscaRequirements, Map componentCache) { + boolean result; + List filteredRelations = relations.stream() + .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(filteredRelations)) { + result = true; + } else { + result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, + component.getComponentInstances(), rel, toscaRequirements, componentCache)).findFirst().isPresent(); + } + return result; + } + + private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, + List instancesList, RequirementCapabilityRelDef rel, + List> toscaRequirements, Map componentCache) { + + boolean result = true; + Map> reqMap = fromOriginComponent.getRequirements(); + RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); + Either getOriginRes = null; + Optional reqOpt = null; + Component toOriginComponent = null; + Optional cap = null; + + ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) + .findFirst().orElse(null); + if (toInstance == null) { + log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), + rel.getToNode()); + result = false; + } + if (result) { + reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId()); + if (!reqOpt.isPresent()) { + log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreCapabilities(false); + getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); + if (getOriginRes.isRight()) { + log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", + reqOpt.get().getName(), toInstance.getActualComponentUid()); + result = false; + } + } + if (result) { + toOriginComponent = getOriginRes.left().value(); + cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() + .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst(); + if (!cap.isPresent()) { + cap = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); + if(!cap.isPresent()){ + result = false; + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + } + } + if (result) { + result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), + reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache); + } + return result; + } + + private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) { + return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId())); + } + + private Optional findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { + Optional cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst(); + if (!cap.isPresent()) { + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + return cap; + } + + private boolean buildAndAddRequirement(List> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map componentCache) { + boolean result = true; + Either buildReqNameRes = null; + List reducedPath = capability.getPath(); + if(capability.getOwnerId() !=null){ + reducedPath = capabiltyRequirementConvertor.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() ); + } + Either buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, + toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability()); + if (buildCapNameRes.isRight()) { + log.debug( + "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + result = false; + } + if (result) { + buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, fromOriginComponent, + requirement.getPath(), reqAndRelationshipPair.getRequirement()); + if (buildReqNameRes.isRight()) { + log.debug( + "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); + Map toscaReqMap = new HashMap<>(); + toscaRequirement.setNode(toInstance.getName()); + toscaRequirement.setCapability(buildCapNameRes.left().value()); + toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); + toscaRequirements.add(toscaReqMap); + } + return result; + } + + private Optional findRequirement(Component fromOriginComponent, Map> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) { + for(List reqList: reqMap.values()){ + Optional reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst(); + if(reqOpt.isPresent()){ + return reqOpt; + } + } + return Optional.empty(); + } + + /** + * Allows detecting the requirement belonging to the received relationship + * The detection logic is: A requirement belongs to a relationship IF 1.The + * name of the requirement equals to the "requirement" field of the + * relation; AND 2. In case of a non-atomic resource, OwnerId of the + * requirement equals to requirementOwnerId of the relation OR uniqueId of + * toInstance equals to capabilityOwnerId of the relation + */ + private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) { + if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())){ + log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}", + requirement.getName(), reqAndRelationshipPair.getRequirement()); + return false; + } + if (!ModelConverter.isAtomicComponent(originComponent)) + return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent); + return true; + } + + private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) { + return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())); + } + + private boolean isCvfc(Component component) { + if (component.getComponentType() != ComponentTypeEnum.RESOURCE) + return false; + return ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; + } + + private Either convertCapabilities(Component component, + SubstitutionMapping substitutionMappings, Map componentCache) { + + Either result = Either.left(substitutionMappings); + Either, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor + .convertSubstitutionMappingCapabilities(componentCache, component); + if (toscaCapabilitiesRes.isRight()) { + result = Either.right(toscaCapabilitiesRes.right().value()); + log.error("Failed convert capabilities for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { + substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); + log.debug("Finish convert capabilities for the component {}. ", component.getName()); + } + log.debug("Finished to convert capabilities for the component {}. ", component.getName()); + return result; + } + + private Either convertCapabilities(Component component, ToscaNodeType nodeType, + Map dataTypes) { + Map toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, + dataTypes); + if (!toscaCapabilities.isEmpty()) { + nodeType.setCapabilities(toscaCapabilities); + } + log.debug("Finish convert Capabilities for node type"); + + return Either.left(nodeType); + } + + private static class CustomRepresenter extends Representer { + public CustomRepresenter() { + super(); + // null representer is exceptional and it is stored as an instance + // variable. + this.nullRepresenter = new RepresentNull(); + + } + + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, + Tag customTag) { + if (propertyValue == null) { + return null; + } else { + // skip not relevant for Tosca property + if ("dependencies".equals(property.getName())) { + return null; + } + NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + + return "_defaultp_".equals(property.getName()) + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; + } + } + + @Override + protected MappingNode representJavaBean(Set properties, Object javaBean) { + // remove the bean type from the output yaml (!! ...) + if (!classTags.containsKey(javaBean.getClass())) + addClassTag(javaBean.getClass(), Tag.MAP); + + return super.representJavaBean(properties, javaBean); + } + + private class RepresentNull implements Represent { + @Override + public Node representData(Object data) { + // possible values are here http://yaml.org/type/null.html + return representScalar(Tag.NULL, ""); + } + } + } + + private static class UnsortedPropertyUtils extends PropertyUtils { + @Override + protected Set createPropertySet(Class type, BeanAccess bAccess) + throws IntrospectionException { + Collection fields = getPropertiesMap(type, BeanAccess.FIELD).values(); + return new LinkedHashSet<>(fields); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java index 6b1895b6ec..49fd91cfed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java @@ -20,30 +20,30 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; + public class ToscaRepresentation { - private String mainYaml; - private List> dependencies; + private String mainYaml; + private List> dependencies; - public String getMainYaml() { - return mainYaml; - } + public String getMainYaml() { + return mainYaml; + } - public void setMainYaml(String mainYaml) { - this.mainYaml = mainYaml; - } + public void setMainYaml(String mainYaml) { + this.mainYaml = mainYaml; + } - public List> getDependencies() { - return dependencies; - } + public List> getDependencies() { + return dependencies; + } - public void setDependencies(List> dependancies) { - this.dependencies = dependancies; - } + public void setDependencies(List> dependancies) { + this.dependencies = dependancies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java index 0c54e7229e..8abaaf73f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java @@ -20,92 +20,88 @@ package org.openecomp.sdc.be.tosca; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Component; +import java.lang.reflect.Field; +import java.util.*; + public class ToscaUtils { - public static boolean isComplexVfc(Component component) { - if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (ResourceTypeEnum.CVFC == resourceType) { - return true; - } - } - return false; - } - - public static Map objectToMap(Object objectToConvert, Class clazz) throws IllegalArgumentException, IllegalAccessException { - Map map = new HashMap<>(); - List fields = new ArrayList<>(); - - fields = getAllFields(fields, clazz); - - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(objectToConvert)); - } - return map; - } - - public static List getAllFields(List fields, Class type) { - fields.addAll(Arrays.asList(type.getDeclaredFields())); - - if (type.getSuperclass() != null) { - fields = getAllFields(fields, type.getSuperclass()); - } - return fields; - } - - public static class SubstituitionEntry{ - - private String fullName = ""; - private String sourceName = ""; - private String owner = ""; - - public SubstituitionEntry() {} - - public SubstituitionEntry(String fullName, String sourceName, String owner) { - if(fullName != null) - this.fullName = fullName; - if(sourceName != null) - this.sourceName = sourceName; - if(owner != null) - this.owner = owner; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getSourceName() { - return sourceName; - } - - public void setSourceName(String sourceName) { - this.sourceName = sourceName; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - } - + public static boolean isComplexVfc(Component component) { + if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (ResourceTypeEnum.CVFC == resourceType) { + return true; + } + } + return false; + } + + public static Map objectToMap(Object objectToConvert, Class clazz) throws IllegalArgumentException, IllegalAccessException { + Map map = new HashMap<>(); + List fields = new ArrayList<>(); + + fields = getAllFields(fields, clazz); + + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(objectToConvert)); + } + return map; + } + + public static List getAllFields(List fields, Class type) { + fields.addAll(Arrays.asList(type.getDeclaredFields())); + + if (type.getSuperclass() != null) { + fields = getAllFields(fields, type.getSuperclass()); + } + return fields; + } + + public static class SubstituitionEntry{ + + private String fullName = ""; + private String sourceName = ""; + private String owner = ""; + + public SubstituitionEntry() {} + + public SubstituitionEntry(String fullName, String sourceName, String owner) { + if(fullName != null) + this.fullName = fullName; + if(sourceName != null) + this.sourceName = sourceName; + if(owner != null) + this.owner = owner; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java index 0c586c7043..f1a7dcb9e5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java @@ -21,23 +21,23 @@ package org.openecomp.sdc.be.tosca.model; public class EntrySchema { - private String type; - private String description; + private String type; + private String description; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java index 70b05b8158..1bb865f562 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java @@ -22,13 +22,13 @@ package org.openecomp.sdc.be.tosca.model; public interface IToscaMetadata { - public void setName(String name); + public void setName(String name); - public void setInvariantUUID(String invariantUUID); + public void setInvariantUUID(String invariantUUID); - public void setUUID(String uUID); + public void setUUID(String uUID); - public void setVersion(String version); - - public void setCustomizationUUID(String customizationUUID); + public void setVersion(String version); + + public void setCustomizationUUID(String customizationUUID); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java index 5dc8ddee2a..bbbb303900 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java @@ -23,36 +23,36 @@ package org.openecomp.sdc.be.tosca.model; import java.util.Map; public class SubstitutionMapping { - private String node_type; - private Map capabilities; - private Map requirements; - - public SubstitutionMapping() { - super(); - // TODO Auto-generated constructor stub - } - - public String getNode_type() { - return node_type; - } - - public void setNode_type(String node_type) { - this.node_type = node_type; - } - - public Map getCapabilities() { - return capabilities; - } - - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } - - public Map getRequirements() { - return requirements; - } - - public void setRequirements(Map requirements) { - this.requirements = requirements; - } + private String node_type; + private Map capabilities; + private Map requirements; + + public SubstitutionMapping() { + super(); + // TODO Auto-generated constructor stub + } + + public String getNode_type() { + return node_type; + } + + public void setNode_type(String node_type) { + this.node_type = node_type; + } + + public Map getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } + + public Map getRequirements() { + return requirements; + } + + public void setRequirements(Map requirements) { + this.requirements = requirements; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java index 2688e5e6b3..d26fd0447c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java @@ -25,56 +25,56 @@ import java.util.Map; public class ToscaCapability { - private String type; - private String description; + private String type; + private String description; - private List occurrences; + private List occurrences; - private List valid_source_types; + private List valid_source_types; - private Map properties; + private Map properties; - public List getValid_source_types() { - return valid_source_types; - } + public List getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List valid_source_types) { + this.valid_source_types = valid_source_types; + } - public ToscaCapability() { - } + public ToscaCapability() { + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public List getOccurrences() { - return occurrences; - } + public List getOccurrences() { + return occurrences; + } - public void setOccurrences(List occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List occurrences) { + this.occurrences = occurrences; + } - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java index b91cffa5be..2c5e095b8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java @@ -24,46 +24,46 @@ import java.util.List; import java.util.Map; public class ToscaGroupTemplate { - private String type; - List members; - private IToscaMetadata metadata; - private Map properties; + private String type; + List members; + private IToscaMetadata metadata; + private Map properties; - public ToscaGroupTemplate() { - super(); + public ToscaGroupTemplate() { + super(); - } + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public List getMembers() { - return members; - } + public List getMembers() { + return members; + } - public void setMembers(List members) { - this.members = members; - } + public void setMembers(List members) { + this.members = members; + } - public IToscaMetadata getMetadata() { - return metadata; - } + public IToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(IToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(IToscaMetadata metadata) { + this.metadata = metadata; + } - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java index 4f91e211cc..69907beaec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java @@ -21,200 +21,200 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaMetadata implements IToscaMetadata { - private String invariantUUID; - private String UUID; - private String customizationUUID; - private String version; - private String name; - private String description; - private String type; - private String category; - private String subcategory; - private String resourceVendor; - private String resourceVendorRelease; - private String resourceVendorModelNumber; - private String serviceType; - private String serviceRole; - private Boolean serviceEcompNaming; - private Boolean ecompGeneratedNaming; - private String namingPolicy; - private String sourceModelInvariant; - private String environmentContext; - private String sourceModelName; - private String sourceModelUuid; - - - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getInvariantUUID() { - return invariantUUID; - } - - @Override - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - public String getUUID() { - return UUID; - } - - @Override - public void setUUID(String uUID) { - UUID = uUID; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } - - public String getResourceVendor() { - return resourceVendor; - } - - public void setResourceVendor(String resourceVendor) { - this.resourceVendor = resourceVendor; - } - - public String getResourceVendorRelease() { - return resourceVendorRelease; - } - - public void setResourceVendorRelease(String resourceVendorRelease) { - this.resourceVendorRelease = resourceVendorRelease; - } - - public String getResourceVendorModelNumber() { - return resourceVendorModelNumber; - } - - public void setResourceVendorModelNumber(String resourceVendorModelNumber) { - this.resourceVendorModelNumber = resourceVendorModelNumber; - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceRole() { - return serviceRole; - } - - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; - } - - public Boolean isEcompGeneratedNaming() { - return ecompGeneratedNaming; - } - - public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { - this.ecompGeneratedNaming = ecompGeneratedNaming; - } - - public String isNamingPolicy() { - return namingPolicy; - } - - public void setNamingPolicy(String namingPolicy) { - this.namingPolicy = namingPolicy; - } - - public Boolean getServiceEcompNaming() { - return serviceEcompNaming; - } - - public void setServiceEcompNaming(Boolean serviceEcompNaming) { - this.serviceEcompNaming = serviceEcompNaming; - } - - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - public String getCustomizationUUID() { - return customizationUUID; - } - - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public String getSourceModelInvariant() { - return sourceModelInvariant; - } - - public void setSourceModelInvariant(String sourceModelInvariant) { - this.sourceModelInvariant = sourceModelInvariant; - } - - public String getSourceModelName() { - return sourceModelName; - } - - public void setSourceModelName(String sourceModelName) { - this.sourceModelName = sourceModelName; - } - - public String getSourceModelUuid() { - return sourceModelUuid; - } - - public void setSourceModelUuid(String sourceModelUuid) { - this.sourceModelUuid = sourceModelUuid; - } - - - - public String getEnvironmentContext() { - return environmentContext; - } - - public void setEnvironmentContext(String environmentContext) { - this.environmentContext = environmentContext; - } + private String invariantUUID; + private String UUID; + private String customizationUUID; + private String version; + private String name; + private String description; + private String type; + private String category; + private String subcategory; + private String resourceVendor; + private String resourceVendorRelease; + private String resourceVendorModelNumber; + private String serviceType; + private String serviceRole; + private Boolean serviceEcompNaming; + private Boolean ecompGeneratedNaming; + private String namingPolicy; + private String sourceModelInvariant; + private String environmentContext; + private String sourceModelName; + private String sourceModelUuid; + + + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + @Override + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getUUID() { + return UUID; + } + + @Override + public void setUUID(String uUID) { + UUID = uUID; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + public String getResourceVendor() { + return resourceVendor; + } + + public void setResourceVendor(String resourceVendor) { + this.resourceVendor = resourceVendor; + } + + public String getResourceVendorRelease() { + return resourceVendorRelease; + } + + public void setResourceVendorRelease(String resourceVendorRelease) { + this.resourceVendorRelease = resourceVendorRelease; + } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public Boolean isEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String isNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getServiceEcompNaming() { + return serviceEcompNaming; + } + + public void setServiceEcompNaming(Boolean serviceEcompNaming) { + this.serviceEcompNaming = serviceEcompNaming; + } + + public String getVersion() { + return version; + } + + @Override + public void setVersion(String version) { + this.version = version; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public String getSourceModelInvariant() { + return sourceModelInvariant; + } + + public void setSourceModelInvariant(String sourceModelInvariant) { + this.sourceModelInvariant = sourceModelInvariant; + } + + public String getSourceModelName() { + return sourceModelName; + } + + public void setSourceModelName(String sourceModelName) { + this.sourceModelName = sourceModelName; + } + + public String getSourceModelUuid() { + return sourceModelUuid; + } + + public void setSourceModelUuid(String sourceModelUuid) { + this.sourceModelUuid = sourceModelUuid; + } + + + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java index b2d7ef5ab6..c27944e8ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java @@ -24,50 +24,58 @@ import java.util.List; import java.util.Map; public class ToscaNodeTemplate { - private String type; - private ToscaMetadata metadata; - private Map properties; - private List> requirements; - private Map capabilities; + private String type; + private ToscaMetadata metadata; + private String description; + private Map properties; + private List> requirements; + private Map capabilities; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } - public List> getRequirements() { - return requirements; - } + public List> getRequirements() { + return requirements; + } - public void setRequirements(List> requirements) { - this.requirements = requirements; - } + public void setRequirements(List> requirements) { + this.requirements = requirements; + } - public Map getCapabilities() { - return capabilities; - } + public Map getCapabilities() { + return capabilities; + } - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java index df9070f49c..4f56cc3bef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java @@ -24,64 +24,64 @@ import java.util.List; import java.util.Map; public class ToscaNodeType { - public ToscaNodeType() { - } + public ToscaNodeType() { + } - private ToscaMetadata metadata; - private String derived_from; - private String description; + private ToscaMetadata metadata; + private String derived_from; + private String description; - private Map properties; - private Map capabilities; + private Map properties; + private Map capabilities; - private List> requirements; + private List> requirements; - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } - public Map getCapabilities() { - return capabilities; - } + public Map getCapabilities() { + return capabilities; + } - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map capabilities) { + this.capabilities = capabilities; + } - public List> getRequirements() { - return requirements; - } + public List> getRequirements() { + return requirements; + } - public void setRequirements(List> requirements) { - this.requirements = requirements; - } + public void setRequirements(List> requirements) { + this.requirements = requirements; + } - public String getDerived_from() { - return derived_from; - } + public String getDerived_from() { + return derived_from; + } - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } + public void setDerived_from(String derived_from) { + this.derived_from = derived_from; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java index 8b5c60b1d4..e1ac69fbe0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java @@ -22,62 +22,62 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaProperty { - private String type; - private Object _defaultp_; - private String description; - private Boolean required; - private EntrySchema entry_schema; - private String status; - - public EntrySchema getEntry_schema() { - return entry_schema; - } - - public void setEntry_schema(EntrySchema entry_schema) { - this.entry_schema = entry_schema; - } - - public ToscaProperty() { - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Object getDefaultp() { - return _defaultp_; - } - - public void setDefaultp(Object defaultp) { - this._defaultp_ = defaultp; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Boolean getRequired() { - return required; - } - - public void setRequired(Boolean required) { - this.required = required; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } + private String type; + private Object _defaultp_; + private String description; + private Boolean required; + private EntrySchema entry_schema; + private String status; + + public EntrySchema getEntry_schema() { + return entry_schema; + } + + public void setEntry_schema(EntrySchema entry_schema) { + this.entry_schema = entry_schema; + } + + public ToscaProperty() { + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Object getDefaultp() { + return _defaultp_; + } + + public void setDefaultp(Object defaultp) { + this._defaultp_ = defaultp; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java index 21fdc9f722..35d5c4e6e1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java @@ -25,21 +25,21 @@ import java.util.Map; public class ToscaRequirement extends ToscaTemplateRequirement { - private List occurrences; + private List occurrences; - public ToscaRequirement() { - } + public ToscaRequirement() { + } - public List getOccurrences() { - return occurrences; - } + public List getOccurrences() { + return occurrences; + } - public void setOccurrences(List occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List occurrences) { + this.occurrences = occurrences; + } - public Map toMap() throws IllegalArgumentException, IllegalAccessException { - return super.toMap(); - } + public Map toMap() throws IllegalArgumentException, IllegalAccessException { + return super.toMap(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java index e80d52167c..387238206c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java @@ -20,71 +20,71 @@ package org.openecomp.sdc.be.tosca.model; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; +import java.util.Map; + public class ToscaTemplate { - private String tosca_definitions_version; - private ToscaMetadata metadata; - private List>> imports; - private Map node_types; - private ToscaTopolgyTemplate topology_template; + private String tosca_definitions_version; + private ToscaMetadata metadata; + private List>> imports; + private Map node_types; + private ToscaTopolgyTemplate topology_template; - private List> dependencies; + private List> dependencies; - public ToscaTemplate(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public ToscaTemplate(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public Map getNode_types() { - return node_types; - } + public Map getNode_types() { + return node_types; + } - public void setNode_types(Map node_types) { - this.node_types = node_types; - } + public void setNode_types(Map node_types) { + this.node_types = node_types; + } - public List>> getImports() { - return imports; - } + public List>> getImports() { + return imports; + } - public void setImports(List>> imports) { - this.imports = imports; - } + public void setImports(List>> imports) { + this.imports = imports; + } - public String getTosca_definitions_version() { - return tosca_definitions_version; - } + public String getTosca_definitions_version() { + return tosca_definitions_version; + } - public void setTosca_definitions_version(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } - public ToscaTopolgyTemplate getTopology_template() { - return topology_template; - } + public ToscaTopolgyTemplate getTopology_template() { + return topology_template; + } - public void setTopology_template(ToscaTopolgyTemplate topology_template) { - this.topology_template = topology_template; - } + public void setTopology_template(ToscaTopolgyTemplate topology_template) { + this.topology_template = topology_template; + } - public List> getDependencies() { - return dependencies; - } + public List> getDependencies() { + return dependencies; + } - public void setDependencies(List> dependencies) { - this.dependencies = dependencies; - } + public void setDependencies(List> dependencies) { + this.dependencies = dependencies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java index 9adb9edfe1..68341079c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java @@ -24,23 +24,23 @@ import java.util.List; import java.util.Map; public class ToscaTemplateCapability { - private List valid_source_types; - private Map properties; + private List valid_source_types; + private Map properties; - public List getValid_source_types() { - return valid_source_types; - } + public List getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List valid_source_types) { + this.valid_source_types = valid_source_types; + } - public Map getProperties() { - return properties; - } + public Map getProperties() { + return properties; + } - public void setProperties(Map properties) { - this.properties = properties; - } + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java index 71bae81f9c..7a77c4f47c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java @@ -25,44 +25,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTemplateRequirement { - private String capability; - private String node; - private String relationship; + private String capability; + private String node; + private String relationship; - public ToscaTemplateRequirement() { - } + public ToscaTemplateRequirement() { + } - public String getCapability() { - return capability; - } + public String getCapability() { + return capability; + } - public void setCapability(String capability) { - this.capability = capability; - } + public void setCapability(String capability) { + this.capability = capability; + } - public String getNode() { - return node; - } + public String getNode() { + return node; + } - public void setNode(String node) { - this.node = node; - } + public void setNode(String node) { + this.node = node; + } - public String getRelationship() { - return relationship; - } + public String getRelationship() { + return relationship; + } - public void setRelationship(String relationship) { - this.relationship = relationship; - } + public void setRelationship(String relationship) { + this.relationship = relationship; + } - public Map toMap() throws IllegalArgumentException, IllegalAccessException { - Map map = new HashMap<>(); - Field[] fields = this.getClass().getDeclaredFields(); - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(this)); - } - return map; - } + public Map toMap() throws IllegalArgumentException, IllegalAccessException { + Map map = new HashMap<>(); + Field[] fields = this.getClass().getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(this)); + } + return map; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java index df285c6ad9..8ef32cb06f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java @@ -24,44 +24,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTopolgyTemplate { - private Map inputs; - private Map node_templates; - private Map groups; - private SubstitutionMapping substitution_mappings; + private Map inputs; + private Map node_templates; + private Map groups; + private SubstitutionMapping substitution_mappings; - public Map getNode_templates() { - return node_templates; - } + public Map getNode_templates() { + return node_templates; + } - public void setNode_templates(Map node_templates) { - this.node_templates = node_templates; - } + public void setNode_templates(Map node_templates) { + this.node_templates = node_templates; + } - public Map getGroups() { - return groups; - } + public Map getGroups() { + return groups; + } - public void addGroups(Map groups) { - if ( this.groups == null ){ - this.groups = new HashMap<>(); - } - this.groups.putAll(groups); - } + public void addGroups(Map groups) { + if ( this.groups == null ){ + this.groups = new HashMap<>(); + } + this.groups.putAll(groups); + } - public SubstitutionMapping getSubstitution_mappings() { - return substitution_mappings; - } + public SubstitutionMapping getSubstitution_mappings() { + return substitution_mappings; + } - public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { - this.substitution_mappings = substitution_mapping; - } + public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { + this.substitution_mappings = substitution_mapping; + } - public Map getInputs() { - return inputs; - } + public Map getInputs() { + return inputs; + } - public void setInputs(Map inputs) { - this.inputs = inputs; - } + public void setInputs(Map inputs) { + this.inputs = inputs; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java index 26ce118a1a..198e233fde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java @@ -22,54 +22,54 @@ package org.openecomp.sdc.be.tosca.model; public class VfModuleToscaMetadata implements IToscaMetadata { - private String vfModuleModelName; - private String vfModuleModelInvariantUUID; - private String vfModuleModelUUID; - private String vfModuleModelVersion; - private String vfModuleModelCustomizationUUID; + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelUUID; + private String vfModuleModelVersion; + private String vfModuleModelCustomizationUUID; - @Override - public void setName(String name) { - vfModuleModelName = name; - } + @Override + public void setName(String name) { + vfModuleModelName = name; + } - @Override - public void setInvariantUUID(String invariantUUID) { - vfModuleModelInvariantUUID = invariantUUID; - } + @Override + public void setInvariantUUID(String invariantUUID) { + vfModuleModelInvariantUUID = invariantUUID; + } - @Override - public void setUUID(String uUID) { - vfModuleModelUUID = uUID; - } + @Override + public void setUUID(String uUID) { + vfModuleModelUUID = uUID; + } - @Override - public void setVersion(String version) { - vfModuleModelVersion = version; - } + @Override + public void setVersion(String version) { + vfModuleModelVersion = version; + } - public String getVfModuleModelName() { - return vfModuleModelName; - } + public String getVfModuleModelName() { + return vfModuleModelName; + } - public String getVfModuleModelInvariantUUID() { - return vfModuleModelInvariantUUID; - } + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } - public String getVfModuleModelUUID() { - return vfModuleModelUUID; - } + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } - public String getVfModuleModelVersion() { - return vfModuleModelVersion; - } + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } - public String getVfModuleModelCustomizationUUID() { - return vfModuleModelCustomizationUUID; - } + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } - public void setCustomizationUUID(String customizationUUID) { - this.vfModuleModelCustomizationUUID = customizationUUID; - } + public void setCustomizationUUID(String customizationUUID) { + this.vfModuleModelCustomizationUUID = customizationUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java new file mode 100644 index 0000000000..c4905d005e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.be.tosca.utils; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; + +import java.util.*; + +/** + * @author KATYR + * @since November 19, 2017 + */ + +public class ForwardingPathToscaUtil { + public static final String FORWARDS_TO_TOSCA_NAME = + "org.openecomp.relationships.ForwardsTo"; + public static final String PROTOCOL = "protocol"; + public static final String PORTS_RANGE = "target_range"; + public static final String FORWARDER = "forwarder"; + + public static void addForwardingPaths(Service service, Map + nodeTemplates, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map originComponents, ToscaOperationFacade toscaOperationFacade) { + for (String forwardingPathName : service.getForwardingPaths().keySet()) { + ToscaNodeTemplate forwardingPathNodeTemplate = + new ToscaNodeTemplate(); + final ForwardingPathDataDefinition path = + service.getForwardingPaths().get(forwardingPathName); + forwardingPathNodeTemplate.setType(path.getToscaResourceName()); + + if (Objects.nonNull(path.getDescription())) { + forwardingPathNodeTemplate.setDescription(path + .getDescription()); + } + Map props = new HashMap<>(); + if (Objects.nonNull(path.getDestinationPortNumber())) { + props.put(PORTS_RANGE, Collections.singletonList(path.getDestinationPortNumber())); + } + if (Objects.nonNull(path.getProtocol())) { + props.put(PROTOCOL, path.getProtocol()); + } + if (MapUtils.isNotEmpty(props)) { + forwardingPathNodeTemplate.setProperties(props); + } + + final List pathElements = + path.getPathElements() + .getListToscaDataDefinition(); + forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements, + service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade)); + + nodeTemplates.put(path.getName(), forwardingPathNodeTemplate); + } + + } + + private static List> convertPathElementsToRequirements( + List pathElements, Service service, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map originComponents,ToscaOperationFacade toscaOperationFacade) { + List> toscaRequirements = new ArrayList<>(); + for (int i = 0; i <= pathElements.size() -1 ; i++) { + final ForwardingPathElementDataDefinition element = pathElements.get(i); + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element.getFromNode()))); + if ( i == pathElements.size() -1) { + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element + .getToNode()))); + } + } + return toscaRequirements; + + } + + private static String fetchNodeName(Service service, String nodeId) { + if (service.getComponentInstanceById(nodeId).isPresent()) { + return service.getComponentInstanceById(nodeId).get().getName(); + } else { + return ""; + } + } + + + private static Map handleSingleReq( + String fromCP, String fromNode) { + Map toscaReqMap = new HashMap<>(); + ToscaTemplateRequirement firstReq = new ToscaTemplateRequirement(); + firstReq.setRelationship(FORWARDS_TO_TOSCA_NAME); //todo + firstReq.setCapability(fromCP); + firstReq.setNode(fromNode); + toscaReqMap.put(FORWARDER, firstReq); + + return toscaReqMap; + } + + /** + * @todo handle errors. + */ + private static String fetchCPName(Service service, String nodeID, String cpName, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map originComponents, ToscaOperationFacade toscaOperationFacade) { + Optional componentInstance = service.getComponentInstanceById(nodeID); + ComponentInstance componentInstanceVal = componentInstance.get(); + String name = componentInstanceVal.getNormalizedName(); + Component component = originComponents.get(componentInstanceVal.getComponentUid()); + if(componentInstanceVal.getIsProxy()){ + component = originComponents.get(componentInstanceVal.getSourceModelUid()); + if (component == null) { + component = toscaOperationFacade.getToscaFullElement(componentInstanceVal.getSourceModelUid()).left().value(); + } + + } + CapabilityDefinition capability = componentInstanceVal.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(cpName)).findAny().get(); + List path = capability.getPath(); + List reducedPath = new ArrayList<>(path); + reducedPath.remove(reducedPath.size() - 1); + Either stringBooleanEither = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, component, reducedPath, capability.getName()); + return name + "." + stringBooleanEither.left().value(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java index 6bec3fa938..ee454d72f3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java @@ -20,15 +20,13 @@ package org.openecomp.sdc.be.user; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.List; /** * @@ -36,17 +34,17 @@ import fj.data.Either; * */ public interface IUserBusinessLogic { - public Either getUser(String userId, boolean inTransaction); + public Either getUser(String userId, boolean inTransaction); - public Either createUser(User modifier, User newUser); + public Either createUser(User modifier, User newUser); - public Either updateUserRole(User modifier, String userIdToUpdate, String userRole); + public Either updateUserRole(User modifier, String userIdToUpdate, String userRole); - public Either, ResponseFormat> getAllAdminUsers(ServletContext context); + public Either, ResponseFormat> getAllAdminUsers(ServletContext context); - public Either, ResponseFormat> getUsersList(String userId, List roles, String rolesStr); + public Either, ResponseFormat> getUsersList(String userId, List roles, String rolesStr); - public Either deActivateUser(User modifier, String userUniuqeIdToDeactive); + public Either deActivateUser(User modifier, String userUniuqeIdToDeactive); - public Either authorize(User authUser); + public Either authorize(User authUser); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java index ab58ea7bf0..9397f6d93b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java @@ -25,5 +25,5 @@ package org.openecomp.sdc.be.user; * which may result in ecompRole id change */ public enum Role { - ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST + ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java index ffc5e4f947..f5b33beb7e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java @@ -22,6 +22,6 @@ package org.openecomp.sdc.be.user; public enum UserAdminAction { - ADD_USER, UPDATE_USER, DELET_USER + ADD_USER, UPDATE_USER, DELET_USER } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java index 796b3a78c0..589fdd8de4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java @@ -25,44 +25,44 @@ import java.util.regex.Pattern; public class UserAdminValidator { - private Pattern emailPat; - private Pattern userIdPat; - private Matcher matcher; + private Pattern emailPat; + private Pattern userIdPat; + private Matcher matcher; - private static UserAdminValidator userAdminValidator = null; + private static UserAdminValidator userAdminValidator = null; - public static synchronized UserAdminValidator getInstance() { - if (userAdminValidator == null) { - userAdminValidator = new UserAdminValidator(); - } - return userAdminValidator; - } + public static synchronized UserAdminValidator getInstance() { + if (userAdminValidator == null) { + userAdminValidator = new UserAdminValidator(); + } + return userAdminValidator; + } - private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - private static final String USER_ID_PATTERN = "\\w{1,25}"; + private static final String USER_ID_PATTERN = "\\w{1,25}"; - private UserAdminValidator() { - emailPat = Pattern.compile(EMAIL_PATTERN); - userIdPat = Pattern.compile(USER_ID_PATTERN); - } + private UserAdminValidator() { + emailPat = Pattern.compile(EMAIL_PATTERN); + userIdPat = Pattern.compile(USER_ID_PATTERN); + } - public boolean validateEmail(final String hex) { - matcher = emailPat.matcher(hex); - return matcher.matches(); - } + public boolean validateEmail(final String hex) { + matcher = emailPat.matcher(hex); + return matcher.matches(); + } - public boolean validateUserId(String userId) { - matcher = userIdPat.matcher(userId); - return matcher.matches(); - } + public boolean validateUserId(String userId) { + matcher = userIdPat.matcher(userId); + return matcher.matches(); + } - public boolean validateRole(String role) { - for (Role r : Role.values()) { - if (r.name().equals(role)) { - return true; - } - } - return false; - } + public boolean validateRole(String role) { + for (Role r : Role.values()) { + if (r.name().equals(role)) { + return true; + } + } + return false; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index 90318a6259..324019a5e8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -20,14 +20,7 @@ package org.openecomp.sdc.be.user; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -49,590 +42,592 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.Resource; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component("userBusinessLogic") public class UserBusinessLogic implements IUserBusinessLogic { - private static Logger log = LoggerFactory.getLogger(UserBusinessLogic.class.getName()); - private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance(); - - @Resource - private IUserAdminOperation userAdminOperation; - @Resource - private ComponentsUtils componentsUtils; - @Autowired - private TitanGenericDao titanDao; - - @Override - public Either getUser(String userId, boolean inTransaction) { - return userAdminOperation.getUserData(userId, inTransaction); - } - - @Override - public Either createUser(User modifier, User newUser) { - - ResponseFormat responseFormat; - String modifierUserId = modifier.getUserId(); - - if (modifierUserId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("createUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - Either eitherCreator = getUser(modifierUserId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("createUser method - user is not admin = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - // verify user not exist - User userFromDb = new User(); - // boolean isUserAlreadyExist = false; - Either eitherUserInDB = getUser(newUser.getUserId(), false); - if (eitherUserInDB.isRight()) { - ActionStatus status = eitherUserInDB.right().value(); - if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) { - responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } else {// User exist in DB - userFromDb = eitherUserInDB.left().value(); - // isUserAlreadyExist = true; - if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) { - responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId()); - log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } - - newUser.setStatus(UserStatusEnum.ACTIVE); - - // validate Email - if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) { - log.debug("createUser method - user has invalid email = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - - // validate Role - if (newUser.getRole() == null || newUser.getRole().length() == 0) { - newUser.setRole(Role.DESIGNER.name()); - } else { - if (!userAdminValidator.validateRole(newUser.getRole())) { - log.debug("createUser method - user has invalid role = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - } - - // handle last login if user is import - if (newUser.getLastLoginTime() == null) { - newUser.setLastLoginTime(0L); - } - - Either addOrUpdateUserReq; - - if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user - // exist - // with - // inactive - // state - // - - // update - // user - // data - newUser.setLastLoginTime(0L); - addOrUpdateUserReq = userAdminOperation.updateUserData(newUser); - - } else { // user not exist - create new user - - if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) { - log.debug("createUser method - user has invalid userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId()); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); - return Either.right(responseFormat); - } - addOrUpdateUserReq = userAdminOperation.saveUserData(newUser); - } - - if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) { - log.debug("createUser method - failed to create user"); - Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value()))); - } - log.debug("createUser method - user created"); - User createdUser = addOrUpdateUserReq.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); - handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER); - return Either.left(createdUser); - } - - @Override - public Either updateUserRole(User modifier, String userIdToUpdate, String userRole) { - - ResponseFormat responseFormat; - String modifierUserId = modifier.getUserId(); - - if (modifierUserId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("updateUserRole method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - Either eitherCreator = getUser(modifierUserId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - if (modifier.getUserId().equals(userIdToUpdate)) { - log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - Either userToUpdateReq = getUser(userIdToUpdate, false); - if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) { - log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - if (!userAdminValidator.validateRole(userRole)) { - log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - - User newUser = new User(); - newUser.setRole(userRole); - newUser.setUserId(userIdToUpdate); - User userToUpdate = userToUpdateReq.left().value(); - // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in - // comment until admin will be able to do do check-in/check-out from the - // UI - - Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); - if (userPendingTasksReq.isRight()) { - log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); - } - - List userPendingTasks = userPendingTasksReq.left().value(); - if (!userPendingTasks.isEmpty()) { - log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); - - String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); - String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); - handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.right(responseFormat); - } - // } - Either updateUserReq = userAdminOperation.updateUserData(newUser); - - if (updateUserReq.isRight() || updateUserReq.left().value() == null) { - log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value()))); - } - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - User updatedUser = updateUserReq.left().value(); - handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER); - return Either.left(updatedUser); - } - - @Override - public Either, ResponseFormat> getAllAdminUsers(ServletContext context) { - Either, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null); - - if (response.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value()); - return Either.right(responseFormat); - } - return Either.left(response.left().value()); - } - - @Override - public Either, ResponseFormat> getUsersList(String modifierAttId, List roles, String rolesStr) { - ResponseFormat responseFormat; - User user = new User(); - if (modifierAttId == null) { - user.setUserId("UNKNOWN"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - Either userResult = getUser(modifierAttId, false); - if (userResult.isRight()) { - user.setUserId(modifierAttId); - if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - } else { - responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); - } - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Get users per roles", modifierAttId); - BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId); - - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - user = userResult.left().value(); - Either, ResponseFormat> getResponse = null; - List resultList = new ArrayList<>(); - if (roles != null && !roles.isEmpty()) { - for (String role : roles) { - if (!userAdminValidator.validateRole(role)) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - getResponse = getUsersPerRole(role, user, rolesStr); - resultList.addAll(getResponse.left().value()); - } - } else { - rolesStr = "All"; - getResponse = getUsersPerRole(null, user, rolesStr); - resultList.addAll(getResponse.left().value()); - } - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.left(resultList); - } - - private Either, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) { - ResponseFormat responseFormat; - Either, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name()); - if (response.isRight()) { - responseFormat = componentsUtils.getResponseFormat(response.right().value()); - handleGetUsersListAuditing(user, responseFormat, rolesStr); - return Either.right(responseFormat); - } - return Either.left(response.left().value()); - } - - private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) { - componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat); - } - - private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) { - componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat); - } - - private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) { - componentsUtils.auditUserAccess(actionName, user, responseFormat); - } - - @Override - public Either deActivateUser(User modifier, String userUniuqeIdToDeactive) { - - ResponseFormat responseFormat; - String userId = modifier.getUserId(); - - if (userId == null) { - modifier.setUserId("UNKNOWN"); - log.debug("deActivateUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either eitherCreator = getUser(userId, false); - if (eitherCreator.isRight() || eitherCreator.left().value() == null) { - log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - modifier = eitherCreator.left().value(); - - if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { - log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - if (modifier.getUserId().equals(userUniuqeIdToDeactive)) { - log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId()); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false); - if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) { - log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive)); - } - - User userToDeactivate = getUserToDeleteResponse.left().value(); - if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) { - log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); - handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); - if (userPendingTasksReq.isRight()) { - log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); - } - - List userPendingTasks = userPendingTasksReq.left().value(); - if (userPendingTasks.size() > 0) { - log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); - - String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); - String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; - responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); - handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.right(responseFormat); - } - - Either deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate); - if (deactivateUserReq.isRight()) { - log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value()))); - } - User deactivateUser = deactivateUserReq.left().value(); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER); - return Either.left(deactivateUser); - } - - @Override - public Either authorize(User authUser) { - - ResponseFormat responseFormat; - - String userId = authUser.getUserId(); - - if (userId == null) { - authUser.setUserId("UNKNOWN"); - log.debug("deActivateUser method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } - - Either eitherCreator = getUser(userId, false); - if (eitherCreator.isRight()) { - if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } else { - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser)); - } - } else { - if (eitherCreator.left().value() == null) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - User user = eitherCreator.left().value(); - - String firstName = authUser.getFirstName(); - if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { - user.setFirstName(firstName); - } - - String lastName = authUser.getLastName(); - if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { - user.setLastName(lastName); - } - - String email = authUser.getEmail(); - if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { - user.setEmail(email); - } - - // last login time stamp handle - user.setLastLoginTime(); - - Either updateUserReq = userAdminOperation.updateUserData(user); - - if (updateUserReq.isRight()) { - responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); - handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); - } - - User updatedUser = updateUserReq.left().value(); - - Long lastLoginTime = user.getLastLoginTime(); - if (lastLoginTime != null) { - updatedUser.setLastLoginTime(lastLoginTime); - } else { - updatedUser.setLastLoginTime(new Long(0)); - } - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); - ASDCKpiApi.countUsersAuthorizations(); - return Either.left(updatedUser); - } - - /* - * The method updates user credentials only, the role is neglected The role updated through updateRole method - */ - public Either updateUserCredentials(User updatedUserCred) { - - ResponseFormat responseFormat; - - String userId = updatedUserCred.getUserId(); - - if (userId == null) { - updatedUserCred.setUserId("UNKNOWN"); - log.debug("updateUserCredentials method - user header is missing"); - responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); - handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } - - Either eitherCreator = getUser(userId, false); - if (eitherCreator.isRight()) { - ActionStatus status = eitherCreator.right().value(); - if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); - handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(responseFormat); - } else { - return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred)); - } - } else { - if (eitherCreator.left().value() == null) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - User user = eitherCreator.left().value(); - - String firstName = updatedUserCred.getFirstName(); - if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { - user.setFirstName(firstName); - } - - String lastName = updatedUserCred.getLastName(); - if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { - user.setLastName(lastName); - } - - String email = updatedUserCred.getEmail(); - if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { - user.setEmail(email); - } - - if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) { - if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) { - user.setLastLoginTime(updatedUserCred.getLastLoginTime()); - } - } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) { - user.setLastLoginTime(updatedUserCred.getLastLoginTime()); - } - - Either updateUserReq = userAdminOperation.updateUserData(user); - - if (updateUserReq.isRight()) { - responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); - handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); - } - - User updatedUser = updateUserReq.left().value(); - - responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); - handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); - return Either.left(updatedUser); - } - - private Either, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { - - Either, StorageOperationStatus> result = null; - - try { - UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole()); - Map properties = new HashMap(); - switch (userRole) { - case DESIGNER: - case PRODUCT_STRATEGIST: - case PRODUCT_MANAGER: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - case TESTER: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - case ADMIN: - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPendingTasksList(user, properties); - default: - return Either.left(new ArrayList<>()); - } - } finally { - // commit will be perform outside!!! - if (result == null || result.isRight()) { - log.debug("getUserPendingTasksList failed to perform fetching"); - titanDao.rollback(); - } else { - titanDao.commit(); - } - } - } - - private String getUserPendingTaskStatusByRole(UserRoleEnum role) { - - switch (role) { - case DESIGNER: - case PRODUCT_STRATEGIST: - case PRODUCT_MANAGER: - return "checked-out"; - - case TESTER: - return "in-certification"; - case ADMIN: - return "in-certification/checked-out"; - default: - return ""; - } - } + private static final Logger log = LoggerFactory.getLogger(UserBusinessLogic.class); + private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance(); + + @Resource + private IUserAdminOperation userAdminOperation; + @Resource + private ComponentsUtils componentsUtils; + @Autowired + private TitanGenericDao titanDao; + + @Override + public Either getUser(String userId, boolean inTransaction) { + return userAdminOperation.getUserData(userId, inTransaction); + } + + @Override + public Either createUser(User modifier, User newUser) { + + ResponseFormat responseFormat; + String modifierUserId = modifier.getUserId(); + + if (modifierUserId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("createUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + Either eitherCreator = getUser(modifierUserId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("createUser method - user is not admin = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + // verify user not exist + User userFromDb = new User(); + Either eitherUserInDB = getUser(newUser.getUserId(), false); + if (eitherUserInDB.isRight()) { + ActionStatus status = eitherUserInDB.right().value(); + if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) { + responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } else {// User exist in DB + userFromDb = eitherUserInDB.left().value(); + if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) { + responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId()); + log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } + + newUser.setStatus(UserStatusEnum.ACTIVE); + + // validate Email + if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) { + log.debug("createUser method - user has invalid email = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + + // validate Role + if (newUser.getRole() == null || newUser.getRole().length() == 0) { + newUser.setRole(Role.DESIGNER.name()); + } else { + if (!userAdminValidator.validateRole(newUser.getRole())) { + log.debug("createUser method - user has invalid role = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + } + + // handle last login if user is import + if (newUser.getLastLoginTime() == null) { + newUser.setLastLoginTime(0L); + } + + Either addOrUpdateUserReq; + + if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user + // exist + // with + // inactive + // state + // - + // update + // user + // data + newUser.setLastLoginTime(0L); + addOrUpdateUserReq = userAdminOperation.updateUserData(newUser); + + } else { // user not exist - create new user + + if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) { + log.debug("createUser method - user has invalid userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId()); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER); + return Either.right(responseFormat); + } + addOrUpdateUserReq = userAdminOperation.saveUserData(newUser); + } + + if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) { + log.debug("createUser method - failed to create user"); + Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value()))); + } + log.debug("createUser method - user created"); + User createdUser = addOrUpdateUserReq.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED); + handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER); + return Either.left(createdUser); + } + + @Override + public Either updateUserRole(User modifier, String userIdToUpdate, String userRole) { + + ResponseFormat responseFormat; + String modifierUserId = modifier.getUserId(); + + if (modifierUserId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("updateUserRole method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + Either eitherCreator = getUser(modifierUserId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + if (modifier.getUserId().equals(userIdToUpdate)) { + log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + Either userToUpdateReq = getUser(userIdToUpdate, false); + if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) { + log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + if (!userAdminValidator.validateRole(userRole)) { + log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + + User newUser = new User(); + newUser.setRole(userRole); + newUser.setUserId(userIdToUpdate); + User userToUpdate = userToUpdateReq.left().value(); + // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in + // comment until admin will be able to do do check-in/check-out from the + // UI + + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); + if (userPendingTasksReq.isRight()) { + log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); + } + + List userPendingTasks = userPendingTasksReq.left().value(); + if (!userPendingTasks.isEmpty()) { + log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); + String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); + handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.right(responseFormat); + } + // } + Either updateUserReq = userAdminOperation.updateUserData(newUser); + + if (updateUserReq.isRight() || updateUserReq.left().value() == null) { + log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value()))); + } + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + User updatedUser = updateUserReq.left().value(); + handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER); + return Either.left(updatedUser); + } + + @Override + public Either, ResponseFormat> getAllAdminUsers(ServletContext context) { + Either, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null); + + if (response.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value()); + return Either.right(responseFormat); + } + return Either.left(response.left().value()); + } + + @Override + public Either, ResponseFormat> getUsersList(String modifierAttId, List roles, String rolesStr) { + ResponseFormat responseFormat; + User user = new User(); + if (modifierAttId == null) { + user.setUserId("UNKNOWN"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + Either userResult = getUser(modifierAttId, false); + if (userResult.isRight()) { + user.setUserId(modifierAttId); + if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + } else { + responseFormat = componentsUtils.getResponseFormat(userResult.right().value()); + } + BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId); + + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + user = userResult.left().value(); + Either, ResponseFormat> getResponse = null; + List resultList = new ArrayList<>(); + if (roles != null && !roles.isEmpty()) { + for (String role : roles) { + if (!userAdminValidator.validateRole(role)) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + getResponse = getUsersPerRole(role, user, rolesStr); + resultList.addAll(getResponse.left().value()); + } + } else { + rolesStr = "All"; + getResponse = getUsersPerRole(null, user, rolesStr); + resultList.addAll(getResponse.left().value()); + } + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.left(resultList); + } + + private Either, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) { + ResponseFormat responseFormat; + Either, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name()); + if (response.isRight()) { + responseFormat = componentsUtils.getResponseFormat(response.right().value()); + handleGetUsersListAuditing(user, responseFormat, rolesStr); + return Either.right(responseFormat); + } + return Either.left(response.left().value()); + } + + private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) { + componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat); + } + + private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) { + componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat); + } + + private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) { + componentsUtils.auditUserAccess(actionName, user, responseFormat); + } + + @Override + public Either deActivateUser(User modifier, String userUniuqeIdToDeactive) { + + ResponseFormat responseFormat; + String userId = modifier.getUserId(); + + if (userId == null) { + modifier.setUserId("UNKNOWN"); + log.debug("deActivateUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either eitherCreator = getUser(userId, false); + if (eitherCreator.isRight() || eitherCreator.left().value() == null) { + log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + modifier = eitherCreator.left().value(); + + if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) { + log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + if (modifier.getUserId().equals(userUniuqeIdToDeactive)) { + log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false); + if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) { + log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive)); + } + + User userToDeactivate = getUserToDeleteResponse.left().value(); + if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) { + log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive); + handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); + if (userPendingTasksReq.isRight()) { + log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); + } + + List userPendingTasks = userPendingTasksReq.left().value(); + if (userPendingTasks.size() > 0) { + log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); + String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; + responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); + handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.right(responseFormat); + } + + Either deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate); + if (deactivateUserReq.isRight()) { + log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value()))); + } + User deactivateUser = deactivateUserReq.left().value(); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER); + return Either.left(deactivateUser); + } + + @Override + public Either authorize(User authUser) { + + ResponseFormat responseFormat; + + String userId = authUser.getUserId(); + + if (userId == null) { + authUser.setUserId("UNKNOWN"); + log.debug("deActivateUser method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } + + Either eitherCreator = getUser(userId, false); + if (eitherCreator.isRight()) { + if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } else { + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser)); + } + } else { + if (eitherCreator.left().value() == null) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + User user = eitherCreator.left().value(); + + String firstName = authUser.getFirstName(); + if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { + user.setFirstName(firstName); + } + + String lastName = authUser.getLastName(); + if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { + user.setLastName(lastName); + } + + String email = authUser.getEmail(); + if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { + user.setEmail(email); + } + + // last login time stamp handle + user.setLastLoginTime(); + + Either updateUserReq = userAdminOperation.updateUserData(user); + + if (updateUserReq.isRight()) { + responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); + handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); + } + + User updatedUser = updateUserReq.left().value(); + + Long lastLoginTime = user.getLastLoginTime(); + if (lastLoginTime != null) { + updatedUser.setLastLoginTime(lastLoginTime); + } else { + updatedUser.setLastLoginTime(new Long(0)); + } + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); + ASDCKpiApi.countUsersAuthorizations(); + return Either.left(updatedUser); + } + + /* + * The method updates user credentials only, the role is neglected The role updated through updateRole method + */ + public Either updateUserCredentials(User updatedUserCred) { + + ResponseFormat responseFormat; + + String userId = updatedUserCred.getUserId(); + + if (userId == null) { + updatedUserCred.setUserId("UNKNOWN"); + log.debug("updateUserCredentials method - user header is missing"); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); + handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } + + Either eitherCreator = getUser(userId, false); + if (eitherCreator.isRight()) { + ActionStatus status = eitherCreator.right().value(); + if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS); + handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(responseFormat); + } else { + return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred)); + } + } else { + if (eitherCreator.left().value() == null) { + responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + User user = eitherCreator.left().value(); + + String firstName = updatedUserCred.getFirstName(); + if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) { + user.setFirstName(firstName); + } + + String lastName = updatedUserCred.getLastName(); + if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) { + user.setLastName(lastName); + } + + String email = updatedUserCred.getEmail(); + if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) { + user.setEmail(email); + } + + if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) { + if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) { + user.setLastLoginTime(updatedUserCred.getLastLoginTime()); + } + } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) { + user.setLastLoginTime(updatedUserCred.getLastLoginTime()); + } + + Either updateUserReq = userAdminOperation.updateUserData(user); + + if (updateUserReq.isRight()) { + responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user); + handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user)); + } + + User updatedUser = updateUserReq.left().value(); + + responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); + handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS); + return Either.left(updatedUser); + } + + private Either, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { + + Either, StorageOperationStatus> result = null; + + try { + UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole()); + Map properties = new HashMap(); + switch (userRole) { + case DESIGNER: + case PRODUCT_STRATEGIST: + case PRODUCT_MANAGER: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + case TESTER: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + case ADMIN: + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); + properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + return userAdminOperation.getUserPendingTasksList(user, properties); + default: + return Either.left(new ArrayList<>()); + } + } finally { + // commit will be perform outside!!! + if (result == null || result.isRight()) { + log.debug("getUserPendingTasksList failed to perform fetching"); + titanDao.rollback(); + } else { + titanDao.commit(); + } + } + } + + private String getUserPendingTaskStatusByRole(UserRoleEnum role) { + + switch (role) { + case DESIGNER: + case PRODUCT_STRATEGIST: + case PRODUCT_MANAGER: + return "checked-out"; + + case TESTER: + return "in-certification"; + case ADMIN: + return "in-certification/checked-out"; + default: + return ""; + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java new file mode 100644 index 0000000000..451989ba36 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java @@ -0,0 +1,7 @@ +package org.openecomp.sdc.be.view; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) +public abstract class Mixin { +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java new file mode 100644 index 0000000000..e3d6ca6e10 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.view; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json representation. + */ +@Provider +@Produces(MediaType.APPLICATION_JSON) +public class MixinModelWriter implements MessageBodyWriter { + + @Override + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return hasResponseViewAndMixinTargetAnnotations(annotations) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE); + } + + @Override + public long getSize(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return -1; + } + + @Override + public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + List mixinSourceTargets = getMixinSourceTarget(annotations); + mixinSourceTargets.forEach(mixinSourceTarget -> objectMapper.addMixIn(mixinSourceTarget.getTarget(), mixinSourceTarget.getMixinSource())); + objectMapper.writeValue(entityStream, object); + } + + private List getMixinSourceTarget(Annotation[] annotations) { + return Stream.of(annotations) + .filter(annotation -> annotation.annotationType().equals(ResponseView.class)) + .map(annotation -> (ResponseView) annotation) + .flatMap(responseView -> Stream.of(responseView.mixin())) + .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target())) + .collect(Collectors.toList()); + } + + private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) { + return Stream.of(annotations) + .filter(annotation -> annotation.annotationType().equals(ResponseView.class)) + .map(annotation -> (ResponseView) annotation) + .flatMap(responseView -> Stream.of(responseView.mixin())) + .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class))); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java new file mode 100644 index 0000000000..c04c4f88cb --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.view; + +/** + * A pojo which holds a mapping between a mixin source and its corresponding target class + */ +public class MixinSourceTarget { + + private Class mixinSource; + private Class target; + + MixinSourceTarget(Class mixinSource, Class target) { + this.mixinSource = mixinSource; + this.target = target; + } + + public Class getMixinSource() { + return mixinSource; + } + + public Class getTarget() { + return target; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java new file mode 100644 index 0000000000..cb44250331 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.be.view; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface MixinTarget { + /** + * + * @return the class which is the target for the mixin. (i.e the class to be serialized into a json response) + */ + Class target(); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java new file mode 100644 index 0000000000..16733ed019 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.be.view; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface ResponseView { + /** + * The mixins that will be used when converting the resource's response into a specific view of that response. + * A number of mixins can be declared, each of which corresponds to a different object. + */ + public Class[] mixin(); +} + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java index e70b33a938..d7a0f4b8d1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; public interface ICommitHandler extends IDBType { - DBActionCodeEnum doCommit(); + DBActionCodeEnum doCommit(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java index a36e5fe1b5..20763d04f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.transaction.api; public interface IDBAction { - T doAction(); + T doAction(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java index 4c19e41609..3aa2e9a9d7 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java @@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public interface IDBType { - DBTypeEnum getDBType(); + DBTypeEnum getDBType(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java index 5a10e9029c..ea041359fd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java @@ -20,21 +20,20 @@ package org.openecomp.sdc.common.transaction.api; +import fj.data.Either; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; -import fj.data.Either; - public interface ITransactionSdnc { - TransactionCodeEnum finishTransaction(); + TransactionCodeEnum finishTransaction(); - Either invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData); + Either invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData); - Either invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction); + Either invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction); - Either invokeTitanAction(boolean isLastAction, IDBAction dbAction); + Either invokeTitanAction(boolean isLastAction, IDBAction dbAction); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java index 97a8083e88..a44073971e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java @@ -20,102 +20,105 @@ package org.openecomp.sdc.common.transaction.api; -import java.util.Stack; - import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Stack; + public abstract class RollbackHandler implements IDBType { - private static Logger log = LoggerFactory.getLogger(RollbackHandler.class.getName()); - private Stack dbActionRollbacks; - - private Integer transactionId; - private String userId, actionType; - - protected RollbackHandler(Integer transactionId, String userId, String actionType) { - if (isRollbackForPersistenceData()) { - dbActionRollbacks = new Stack<>(); - } - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; - } - - public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) { - MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS; - if (isRollbackForPersistenceData()) { - dbActionRollbacks.push(rollbackAction); - } else { - result = MethodActivationStatusEnum.NOT_ALLOWED; - } - return result; - } - - public DBActionCodeEnum doRollback() { - DBActionCodeEnum result; - - try { - if (isRollbackForPersistenceData()) { - result = doPersistenceDataRollback(); - } else { - log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - result = doNonPersistenceDataRollback(); - } - if (result != DBActionCodeEnum.SUCCESS) { - log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); - log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); - } - - } catch (Exception e) { - result = DBActionCodeEnum.FAIL_GENERAL; - log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); - log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e); - log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); - } - - return result; - } - - private DBActionCodeEnum doPersistenceDataRollback() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - while (!dbActionRollbacks.empty()) { - log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); - IDBAction rollbackAction = dbActionRollbacks.pop(); - T rollbackResult = rollbackAction.doAction(); - if (!isRollbackResultValid(rollbackResult)) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - } - return result; - } - - /** - * Override for specific logic - * - * @param - */ - public boolean isRollbackResultValid(T rollbackResult) { - return true; - } - - /** - * Override for specific logic - */ - public DBActionCodeEnum doNonPersistenceDataRollback() { - return DBActionCodeEnum.SUCCESS; - } - - protected abstract boolean isRollbackForPersistenceData(); - - /** - * Only Used for Unit Tests ! - */ - public static void setLog(Logger log) { - RollbackHandler.log = log; - } + + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(RollbackHandler.class); + private Stack dbActionRollbacks; + + private Integer transactionId; + private String userId, actionType; + + protected RollbackHandler(Integer transactionId, String userId, String actionType) { + if (isRollbackForPersistenceData()) { + dbActionRollbacks = new Stack<>(); + } + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; + } + + public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) { + MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS; + if (isRollbackForPersistenceData()) { + dbActionRollbacks.push(rollbackAction); + } else { + result = MethodActivationStatusEnum.NOT_ALLOWED; + } + return result; + } + + public DBActionCodeEnum doRollback() { + DBActionCodeEnum result; + + try { + if (isRollbackForPersistenceData()) { + result = doPersistenceDataRollback(); + } else { + log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + result = doNonPersistenceDataRollback(); + } + if (result != DBActionCodeEnum.SUCCESS) { + log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); + log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType); + } + + } catch (Exception e) { + result = DBActionCodeEnum.FAIL_GENERAL; + log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); + log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e); + log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType); + } + + return result; + } + + private DBActionCodeEnum doPersistenceDataRollback() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + while (!dbActionRollbacks.empty()) { + log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType); + IDBAction rollbackAction = dbActionRollbacks.pop(); + T rollbackResult = rollbackAction.doAction(); + if (!isRollbackResultValid(rollbackResult)) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + } + return result; + } + + /** + * Override for specific logic + * + * @param + */ + public boolean isRollbackResultValid(T rollbackResult) { + return true; + } + + /** + * Override for specific logic + */ + public DBActionCodeEnum doNonPersistenceDataRollback() { + return DBActionCodeEnum.SUCCESS; + } + + protected abstract boolean isRollbackForPersistenceData(); + + /** + * Only Used for Unit Tests ! + */ + // TODO test using slf4j-test and remove this + public static void setLog(Logger log) { + RollbackHandler.log = log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java index e90b9618d4..fc7c90509f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java @@ -25,61 +25,61 @@ import org.slf4j.MarkerFactory; public final class TransactionUtils { - private TransactionUtils() { - - } - - public enum DBTypeEnum { - ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT - } - - public enum TransactionCodeEnum { - ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED - } - - public enum TransactionStatusEnum { - OPEN, CLOSED, FAILED_ROLLBACK - } - - public enum DBActionCodeEnum { - SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION - } - - public enum ESActionTypeEnum { - ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT - } - - public enum ActionTypeEnum { - ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE - } - - public static final int MAX_SIZE_TRANSACTION_LIST = 1000; - - public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10; - - public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER"; - - public static final String DUMMY_USER = "udummy"; - - public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR); - - public static class LogMessages { - public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}"; - public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}"; - public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}"; - public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; - public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}"; - public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}"; - public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}"; - public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}"; - public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; - public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}"; - public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}"; - public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}"; - public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}"; - public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}"; - } + private TransactionUtils() { + + } + + public enum DBTypeEnum { + ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT + } + + public enum TransactionCodeEnum { + ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED + } + + public enum TransactionStatusEnum { + OPEN, CLOSED, FAILED_ROLLBACK + } + + public enum DBActionCodeEnum { + SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION + } + + public enum ESActionTypeEnum { + ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT + } + + public enum ActionTypeEnum { + ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE + } + + public static final int MAX_SIZE_TRANSACTION_LIST = 1000; + + public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10; + + public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER"; + + public static final String DUMMY_USER = "udummy"; + + public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR); + + public static class LogMessages { + public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}"; + public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}"; + public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}"; + public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; + public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}"; + public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}"; + public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}"; + public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}"; + public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}"; + public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}"; + public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}"; + public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}"; + public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}"; + public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}"; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java index 33a8d1163b..0d628cf264 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java @@ -23,36 +23,42 @@ package org.openecomp.sdc.common.transaction.impl; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; +import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.common.transaction.api.IDBAction; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ESAction implements IDBAction { - private ESCatalogDAO esCatalogDao; - private ESArtifactData artifactData; - private ESActionTypeEnum esActionType; - - public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { - this.esCatalogDao = esCatalogDao; - this.artifactData = artifactData; - this.esActionType = esActiontype; - } - - @Override - public DBActionCodeEnum doAction() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - try { - if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) { - esCatalogDao.writeArtifact(artifactData); - } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) { - esCatalogDao.deleteArtifact(artifactData.getId()); - } - - } catch (ResourceDAOException daoException) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + private ESCatalogDAO esCatalogDao; + private ESArtifactData artifactData; + private ESActionTypeEnum esActionType; + + public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { + this.esCatalogDao = esCatalogDao; + this.artifactData = artifactData; + this.esActionType = esActiontype; + } + + @Override + public DBActionCodeEnum doAction() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + try { + if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) { + esCatalogDao.writeArtifact(artifactData); + } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) { + esCatalogDao.deleteArtifact(artifactData.getId()); + } + + } catch (ResourceDAOException daoException) { + result = DBActionCodeEnum.FAIL_GENERAL; + log.error("#doAction - {}, es action failed with error : ", result, daoException); + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java index b9fb0d31b7..e17819fcb0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java @@ -20,73 +20,79 @@ package org.openecomp.sdc.common.transaction.impl; +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.exception.ResourceDAOException; +import org.openecomp.sdc.be.tosca.CsarUtils; import org.openecomp.sdc.common.transaction.api.RollbackHandler; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; - -import fj.data.Either; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ESRollbackHandler extends RollbackHandler { - public ESRollbackHandler(Integer transactionId, String userId, String actionType) { - super(transactionId, userId, actionType); - } - - public DBTypeEnum getDBType() { - return DBTypeEnum.ELASTIC_SEARCH; - } - - protected boolean isRollbackForPersistenceData() { - return true; - } - - public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) { - return rollbackResult == DBActionCodeEnum.SUCCESS; - } - - public Either buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { - Either result; - - try { - ESAction esRollbackAction = null; - Either either = esCatalogDao.getArtifact(artifactData.getId()); - - switch (esActiontype) { - case ADD_ARTIFACT: - - if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) { - esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT); - } - break; - case REMOVE_ARTIFACT: - if (either.isLeft()) { - esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT); - } - break; - case UPDATE_ARTIFACT: - - if (either.isLeft()) { - ESArtifactData originalArtifactData = either.left().value(); - esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT); - } - break; - - } - if (esRollbackAction != null) { - result = Either.left(esRollbackAction); - } else { - result = Either.right(MethodActivationStatusEnum.FAILED); - } - } catch (Exception e) { - result = Either.right(MethodActivationStatusEnum.FAILED); - } - - return result; - } + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + public ESRollbackHandler(Integer transactionId, String userId, String actionType) { + super(transactionId, userId, actionType); + } + + public DBTypeEnum getDBType() { + return DBTypeEnum.ELASTIC_SEARCH; + } + + protected boolean isRollbackForPersistenceData() { + return true; + } + + public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) { + return rollbackResult == DBActionCodeEnum.SUCCESS; + } + + public Either buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) { + Either result; + + try { + ESAction esRollbackAction = null; + Either either = esCatalogDao.getArtifact(artifactData.getId()); + + switch (esActiontype) { + case ADD_ARTIFACT: + + if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) { + esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT); + } + break; + case REMOVE_ARTIFACT: + if (either.isLeft()) { + esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT); + } + break; + case UPDATE_ARTIFACT: + + if (either.isLeft()) { + ESArtifactData originalArtifactData = either.left().value(); + esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT); + } + break; + + } + if (esRollbackAction != null) { + result = Either.left(esRollbackAction); + } else { + result = Either.right(MethodActivationStatusEnum.FAILED); + } + } catch (Exception e) { + result = Either.right(MethodActivationStatusEnum.FAILED); + log.error("#buildEsRollbackAction - {}, es rollback failed with error: ", result, e); + } + + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java index 0d2ec387cf..c86241ebf1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java @@ -28,25 +28,25 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public class TitanCommitHandler implements ICommitHandler { - private TitanGenericDao titanGenericDao; - - public TitanCommitHandler(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public DBActionCodeEnum doCommit() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.commit(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } - - @Override - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } + private TitanGenericDao titanGenericDao; + + public TitanCommitHandler(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + @Override + public DBActionCodeEnum doCommit() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + TitanOperationStatus titanStatus = titanGenericDao.commit(); + if (titanStatus != TitanOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } + + @Override + public DBTypeEnum getDBType() { + return DBTypeEnum.TITAN; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java index c0c686723c..89d2b9da8e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java @@ -28,28 +28,28 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; public class TitanRollbackHandler extends RollbackHandler { - private TitanGenericDao titanGenericDao; - - public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) { - super(transactionId, userId, actionType); - this.titanGenericDao = titanGenericDao; - } - - public DBTypeEnum getDBType() { - return DBTypeEnum.TITAN; - } - - protected boolean isRollbackForPersistenceData() { - return false; - } - - public DBActionCodeEnum doNonPersistenceDataRollback() { - DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; - TitanOperationStatus titanStatus = titanGenericDao.rollback(); - if (titanStatus != TitanOperationStatus.OK) { - result = DBActionCodeEnum.FAIL_GENERAL; - } - return result; - } + private TitanGenericDao titanGenericDao; + + public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) { + super(transactionId, userId, actionType); + this.titanGenericDao = titanGenericDao; + } + + public DBTypeEnum getDBType() { + return DBTypeEnum.TITAN; + } + + protected boolean isRollbackForPersistenceData() { + return false; + } + + public DBActionCodeEnum doNonPersistenceDataRollback() { + DBActionCodeEnum result = DBActionCodeEnum.SUCCESS; + TitanOperationStatus titanStatus = titanGenericDao.rollback(); + if (titanStatus != TitanOperationStatus.OK) { + result = DBActionCodeEnum.FAIL_GENERAL; + } + return result; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java index e802e58f27..f366ae214f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.List; - import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.common.transaction.api.ICommitHandler; @@ -31,57 +29,60 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public class CommitManager { - private List commitHandlers; - private Integer transactionId; - private String userId, actionType; - private static Logger log = LoggerFactory.getLogger(CommitManager.class.getName()); - CommitManager(Integer transactionId, String userId, String actionType, List commitHandlers) { - this.commitHandlers = commitHandlers; - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(CommitManager.class); + private List commitHandlers; + private Integer transactionId; + private String userId, actionType; + + CommitManager(Integer transactionId, String userId, String actionType, List commitHandlers) { + this.commitHandlers = commitHandlers; + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; - } + } - public DBActionCodeEnum transactionCommit() { - log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType); - DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS; - ICommitHandler lastHandler = null; - try { - for (ICommitHandler handler : commitHandlers) { - lastHandler = handler; - log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType); - DBActionCodeEnum commitCode = handler.doCommit(); - if (commitCode == DBActionCodeEnum.FAIL_GENERAL) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit on DB " + handler.getDBType().name()); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name()); - log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); - commitResult = DBActionCodeEnum.FAIL_GENERAL; - break; - } - log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit - on DB " + getDBName(lastHandler)); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler)); - log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e); - log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler)); - commitResult = DBActionCodeEnum.FAIL_GENERAL; - } - return commitResult; - } + public DBActionCodeEnum transactionCommit() { + log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType); + DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS; + ICommitHandler lastHandler = null; + try { + for (ICommitHandler handler : commitHandlers) { + lastHandler = handler; + log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType); + DBActionCodeEnum commitCode = handler.doCommit(); + if (commitCode == DBActionCodeEnum.FAIL_GENERAL) { + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name()); + log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); + commitResult = DBActionCodeEnum.FAIL_GENERAL; + break; + } + log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name()); + } + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler)); + log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e); + log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler)); + commitResult = DBActionCodeEnum.FAIL_GENERAL; + } + return commitResult; + } - private String getDBName(ICommitHandler lastHandler) { - String dbName = "Unknown"; - if (lastHandler != null) { - dbName = lastHandler.getDBType().name(); - } - return dbName; - } + private String getDBName(ICommitHandler lastHandler) { + String dbName = "Unknown"; + if (lastHandler != null) { + dbName = lastHandler.getDBType().name(); + } + return dbName; + } - static void setLog(Logger log) { - CommitManager.log = log; - } + // TODO test using slf4j-test and remove this + static void setLog(Logger log) { + CommitManager.log = log; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java index 7098021d1f..80d548ef42 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java @@ -31,56 +31,56 @@ import fj.data.HashMap; import fj.data.List; public class RollbackManager { - private final HashMap rollbackHandlersMap; - private final Integer transactionId; - private final String userId; - private final String actionType; + private final HashMap rollbackHandlersMap; + private final Integer transactionId; + private final String userId; + private final String actionType; - RollbackManager(Integer transactionId, String userId, String actionType, Iterable rollbackHandlers) { - this.transactionId = transactionId; - this.userId = userId; - this.actionType = actionType; - this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i))); - } + RollbackManager(Integer transactionId, String userId, String actionType, Iterable rollbackHandlers) { + this.transactionId = transactionId; + this.userId = userId; + this.actionType = actionType; + this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i))); + } - public DBActionCodeEnum transactionRollback() { - List results = rollbackHandlersMap.values().map(RollbackHandler::doRollback); - boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL); - return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS; - } + public DBActionCodeEnum transactionRollback() { + List results = rollbackHandlersMap.values().map(RollbackHandler::doRollback); + boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL); + return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS; + } - protected Either addRollbackHandler(RollbackHandler rollbackHandler) { - Either result; - if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) { - result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED); - } else { - rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler); - result = Either.left(rollbackHandler); - } - return result; + protected Either addRollbackHandler(RollbackHandler rollbackHandler) { + Either result; + if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) { + result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED); + } else { + rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler); + result = Either.left(rollbackHandler); + } + return result; - } + } - protected Either createRollbackHandler(final DBTypeEnum dbType) { + protected Either createRollbackHandler(final DBTypeEnum dbType) { - RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) { + RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) { - @Override - public DBTypeEnum getDBType() { - return dbType; - } + @Override + public DBTypeEnum getDBType() { + return dbType; + } - @Override - protected boolean isRollbackForPersistenceData() { - return true; - } - }; - return addRollbackHandler(rollbackHandler); - } + @Override + protected boolean isRollbackForPersistenceData() { + return true; + } + }; + return addRollbackHandler(rollbackHandler); + } - protected Either getRollbackHandler(DBTypeEnum dbType) { - // need to swap here because the uses of Either in SDC appears to be opposite of convention - // by convention left is failure; in SDC right is failure - return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap(); - } + protected Either getRollbackHandler(DBTypeEnum dbType) { + // need to swap here because the uses of Either in SDC appears to be opposite of convention + // by convention left is failure; in SDC right is failure + return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java index c05431ac7f..f218744b84 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java @@ -20,11 +20,8 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.Queue; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.annotation.Resource; - +import com.google.common.collect.EvictingQueue; +import com.google.common.collect.Queues; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.common.transaction.api.ITransactionSdnc; @@ -34,70 +31,71 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.google.common.collect.EvictingQueue; -import com.google.common.collect.Queues; +import javax.annotation.Resource; +import java.util.Queue; +import java.util.concurrent.atomic.AtomicInteger; @Component("transactionManager") public class TransactionManager { - private static Logger log = LoggerFactory.getLogger(TransactionManager.class.getName()); - - private AtomicInteger transactionIDCounter = new AtomicInteger(0); - - private Queue transactions; - @Resource - private ESCatalogDAO esCatalogDao; - @Resource - private TitanGenericDao titanGenericDao; - - /** - * userId and actionType parameters are used only for logging purposes. - */ - public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) { - if (transactions == null) { - init(); - } - log.debug("TransactionManager creating new SdncTransaction"); - ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao); - transactions.add(tx); - - return tx; - - } - - private Integer generateTransactionID() { - boolean generatedSuccessfully = false; - int nextId = 0; - - while (!generatedSuccessfully) { - int prevId = transactionIDCounter.get(); - if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) { - resetTransactionId(); - } - nextId = prevId + 1; - generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId); - } - return nextId; - } - - private void resetTransactionId() { - - boolean resetSuccessfully = false; - while (!resetSuccessfully) { - int prevId = transactionIDCounter.get(); - resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0); - } - - } - - private synchronized void init() { - if (transactions == null) { - log.info("TransactionManager Initialized"); - EvictingQueue queue = EvictingQueue - .create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST); - // make thread-safe - transactions = Queues.synchronizedQueue(queue); - } - } + private static final Logger log = LoggerFactory.getLogger(TransactionManager.class); + + private AtomicInteger transactionIDCounter = new AtomicInteger(0); + + private Queue transactions; + @Resource + private ESCatalogDAO esCatalogDao; + @Resource + private TitanGenericDao titanGenericDao; + + /** + * userId and actionType parameters are used only for logging purposes. + */ + public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) { + if (transactions == null) { + init(); + } + log.debug("TransactionManager creating new SdncTransaction"); + ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao); + transactions.add(tx); + + return tx; + + } + + private Integer generateTransactionID() { + boolean generatedSuccessfully = false; + int nextId = 0; + + while (!generatedSuccessfully) { + int prevId = transactionIDCounter.get(); + if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) { + resetTransactionId(); + } + nextId = prevId + 1; + generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId); + } + return nextId; + } + + private void resetTransactionId() { + + boolean resetSuccessfully = false; + while (!resetSuccessfully) { + int prevId = transactionIDCounter.get(); + resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0); + } + + } + + private synchronized void init() { + if (transactions == null) { + log.info("TransactionManager Initialized"); + EvictingQueue queue = EvictingQueue + .create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST); + // make thread-safe + transactions = Queues.synchronizedQueue(queue); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java index 55eff24fa9..bc7b5bde03 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java @@ -20,26 +20,14 @@ package org.openecomp.sdc.common.transaction.mngr; -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.impl.ESCatalogDAO; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.common.config.EcompErrorName; -import org.openecomp.sdc.common.transaction.api.ICommitHandler; -import org.openecomp.sdc.common.transaction.api.IDBAction; -import org.openecomp.sdc.common.transaction.api.ITransactionSdnc; -import org.openecomp.sdc.common.transaction.api.RollbackHandler; -import org.openecomp.sdc.common.transaction.api.TransactionUtils; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.ActionTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum; -import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; +import org.openecomp.sdc.common.transaction.api.*; +import org.openecomp.sdc.common.transaction.api.TransactionUtils.*; import org.openecomp.sdc.common.transaction.impl.ESAction; import org.openecomp.sdc.common.transaction.impl.ESRollbackHandler; import org.openecomp.sdc.common.transaction.impl.TitanCommitHandler; @@ -48,266 +36,264 @@ import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; public class TransactionSdncImpl implements ITransactionSdnc { - private boolean lastActionAlreadyCalled; - private RollbackManager rollbackManager; - private CommitManager commitManager; - private ESCatalogDAO esCatalogDao; - private TitanGenericDao titanGenericDao; - private Integer transactionId; - private TransactionStatusEnum status; - private String userId, actionType; - private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class.getName()); - - TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) { - this.esCatalogDao = esCatalogDao; - this.titanGenericDao = titanGenericDao; - this.transactionId = transactionId; - this.userId = userId; - actionType = actionTypeEnum.name(); - rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers()); - commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers()); - status = TransactionStatusEnum.OPEN; - - } - - private List initCommitHandlers() { - List commitHandlers = new ArrayList<>(); - commitHandlers.add(new TitanCommitHandler(titanGenericDao)); - return commitHandlers; - } - - private List initRollbackHandlers() { - List rolebackHandlers = new ArrayList<>(); - rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao)); - rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType)); - return rolebackHandlers; - } - - private Either invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) { - - Either actionResult; - log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); - if (isLastAction) { - actionResult = getLastActionResult(dbAction, dbType); - } else { - actionResult = getActionResult(dbAction, dbType); - } - - Either result; - boolean isRollbackNedded = actionResult.isRight(); - if (isRollbackNedded) { - TransactionCodeEnum transactionCode = transactionRollback(); - result = Either.right(transactionCode); - } else { - result = Either.left(actionResult.left().value()); - } - return result; - } - - private TransactionCodeEnum transactionRollback() { - - TransactionCodeEnum result; - DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback(); - if (transactionRollback == DBActionCodeEnum.SUCCESS) { - result = TransactionCodeEnum.ROLLBACK_SUCCESS; - log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); - - } else { - result = TransactionCodeEnum.ROLLBACK_FAILED; - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit for transaction " + transactionId); - BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId); - - log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); - } - return result; - } - - public Either invokeTitanAction(boolean isLastAction, IDBAction dbAction) { - Either result; - if (status == TransactionStatusEnum.OPEN) { - result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN); - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - public Either invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) { - - Either result; - MethodActivationStatusEnum addingHandlerResult; - if (status == TransactionStatusEnum.OPEN) { - log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); - Either eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType); - - if (eitherRollbackHandler.isLeft()) { - RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); - addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction); - } else { - addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction); - } - - if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) { - result = invokeAction(isLastAction, dbAction, dbType); - } else { - result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); - } - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) { - log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType); - MethodActivationStatusEnum result; - - Either eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType); - if (eitherRollbackHandler.isRight()) { - result = eitherRollbackHandler.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - addToNewRollbackHandler"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler"); - log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); - log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); - } else { - RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); - rollbackHandler.addRollbackAction(dbRollbackAction); - result = MethodActivationStatusEnum.SUCCESS; - } - - return result; - } - - public Either invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) { - - Either result; - if (status == TransactionStatusEnum.OPEN) { - Either eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH); - if (eitherEsHandler.isRight()) { - result = Either.right(TransactionCodeEnum.INTERNAL_ERROR); - } else { - ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value(); - - Either eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype); - if (eitherEsRollbackAction.isLeft()) { - esHandler.addRollbackAction(eitherEsRollbackAction.left().value()); - result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH); - } else { - result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); - } - - } - } else { - result = handleActionOnClosedTransaction(); - } - updateTransactionStatus(result); - return result; - } - - private void updateTransactionStatus(Either result) { - if (result.isRight()) { - updateTransactionStatus(result.right().value()); - } - - } - - private Either handleActionOnClosedTransaction() { - Either result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - handleActionOnClosedTransaction"); - log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); - return result; - } - - private Either getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { - Either result; - if (isLastActionAlreadyCalled()) { - result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getLastActionResult"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult"); - log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); - } else { - setLastActionAlreadyCalled(true); - result = getActionResult(dataBaseAction, dbType); - } - return result; - } - - private Either getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { - Either result; - try { - T doAction = dataBaseAction.doAction(); - result = Either.left(doAction); - } catch (Exception e) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getActionResult"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult"); - log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType); - - result = Either.right(DBActionCodeEnum.FAIL_GENERAL); - } - return result; - } - - public TransactionCodeEnum finishTransaction() { - TransactionCodeEnum result; - if (status == TransactionStatusEnum.OPEN) { - DBActionCodeEnum transactionCommit = commitManager.transactionCommit(); - if (transactionCommit == DBActionCodeEnum.SUCCESS) { - result = TransactionCodeEnum.SUCCESS; - status = TransactionStatusEnum.CLOSED; - } else { - result = transactionRollback(); - } - } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - finishTransaction"); - BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction"); - log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); - log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); - result = TransactionCodeEnum.TRANSACTION_CLOSED; - } - updateTransactionStatus(result); - return result; - } - - private void updateTransactionStatus(TransactionCodeEnum result) { - switch (result) { - case SUCCESS: - status = TransactionStatusEnum.CLOSED; - break; - case ROLLBACK_SUCCESS: - status = TransactionStatusEnum.CLOSED; - break; - case ROLLBACK_FAILED: - status = TransactionStatusEnum.FAILED_ROLLBACK; - break; - default: - break; - } - - } - - private boolean isLastActionAlreadyCalled() { - return lastActionAlreadyCalled; - } - - private void setLastActionAlreadyCalled(boolean lastAction) { - this.lastActionAlreadyCalled = lastAction; - } - - static void setLog(Logger log) { - TransactionSdncImpl.log = log; - } - - TransactionStatusEnum getStatus() { - return status; - } + + // TODO test using slf4j-test and make this final + private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class); + private boolean lastActionAlreadyCalled; + private RollbackManager rollbackManager; + private CommitManager commitManager; + private ESCatalogDAO esCatalogDao; + private TitanGenericDao titanGenericDao; + private Integer transactionId; + private TransactionStatusEnum status; + private String userId, actionType; + + TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) { + this.esCatalogDao = esCatalogDao; + this.titanGenericDao = titanGenericDao; + this.transactionId = transactionId; + this.userId = userId; + actionType = actionTypeEnum.name(); + rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers()); + commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers()); + status = TransactionStatusEnum.OPEN; + + } + + private List initCommitHandlers() { + List commitHandlers = new ArrayList<>(); + commitHandlers.add(new TitanCommitHandler(titanGenericDao)); + return commitHandlers; + } + + private List initRollbackHandlers() { + List rolebackHandlers = new ArrayList<>(); + rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao)); + rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType)); + return rolebackHandlers; + } + + private Either invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) { + + Either actionResult; + log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); + if (isLastAction) { + actionResult = getLastActionResult(dbAction, dbType); + } else { + actionResult = getActionResult(dbAction, dbType); + } + + Either result; + boolean isRollbackNedded = actionResult.isRight(); + if (isRollbackNedded) { + TransactionCodeEnum transactionCode = transactionRollback(); + result = Either.right(transactionCode); + } else { + result = Either.left(actionResult.left().value()); + } + return result; + } + + private TransactionCodeEnum transactionRollback() { + + TransactionCodeEnum result; + DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback(); + if (transactionRollback == DBActionCodeEnum.SUCCESS) { + result = TransactionCodeEnum.ROLLBACK_SUCCESS; + log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType); + + } else { + result = TransactionCodeEnum.ROLLBACK_FAILED; + BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId); + + log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType); + } + return result; + } + + public Either invokeTitanAction(boolean isLastAction, IDBAction dbAction) { + Either result; + if (status == TransactionStatusEnum.OPEN) { + result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN); + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + public Either invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) { + + Either result; + MethodActivationStatusEnum addingHandlerResult; + if (status == TransactionStatusEnum.OPEN) { + log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType); + Either eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType); + + if (eitherRollbackHandler.isLeft()) { + RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); + addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction); + } else { + addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction); + } + + if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) { + result = invokeAction(isLastAction, dbAction, dbType); + } else { + result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); + } + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) { + log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType); + MethodActivationStatusEnum result; + + Either eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType); + if (eitherRollbackHandler.isRight()) { + result = eitherRollbackHandler.right().value(); + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler"); + log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); + log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType); + } else { + RollbackHandler rollbackHandler = eitherRollbackHandler.left().value(); + rollbackHandler.addRollbackAction(dbRollbackAction); + result = MethodActivationStatusEnum.SUCCESS; + } + + return result; + } + + public Either invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) { + + Either result; + if (status == TransactionStatusEnum.OPEN) { + Either eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH); + if (eitherEsHandler.isRight()) { + result = Either.right(TransactionCodeEnum.INTERNAL_ERROR); + } else { + ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value(); + + Either eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype); + if (eitherEsRollbackAction.isLeft()) { + esHandler.addRollbackAction(eitherEsRollbackAction.left().value()); + result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH); + } else { + result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED); + } + + } + } else { + result = handleActionOnClosedTransaction(); + } + updateTransactionStatus(result); + return result; + } + + private void updateTransactionStatus(Either result) { + if (result.isRight()) { + updateTransactionStatus(result.right().value()); + } + + } + + private Either handleActionOnClosedTransaction() { + Either result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED); + log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType); + return result; + } + + private Either getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { + Either result; + if (isLastActionAlreadyCalled()) { + result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION); + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult"); + log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType); + } else { + setLastActionAlreadyCalled(true); + result = getActionResult(dataBaseAction, dbType); + } + return result; + } + + private Either getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) { + Either result; + try { + T doAction = dataBaseAction.doAction(); + result = Either.left(doAction); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult"); + log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType); + + result = Either.right(DBActionCodeEnum.FAIL_GENERAL); + } + return result; + } + + public TransactionCodeEnum finishTransaction() { + TransactionCodeEnum result; + if (status == TransactionStatusEnum.OPEN) { + DBActionCodeEnum transactionCommit = commitManager.transactionCommit(); + if (transactionCommit == DBActionCodeEnum.SUCCESS) { + result = TransactionCodeEnum.SUCCESS; + status = TransactionStatusEnum.CLOSED; + } else { + result = transactionRollback(); + } + } else { + BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction"); + log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); + log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType); + result = TransactionCodeEnum.TRANSACTION_CLOSED; + } + updateTransactionStatus(result); + return result; + } + + private void updateTransactionStatus(TransactionCodeEnum result) { + switch (result) { + case SUCCESS: + status = TransactionStatusEnum.CLOSED; + break; + case ROLLBACK_SUCCESS: + status = TransactionStatusEnum.CLOSED; + break; + case ROLLBACK_FAILED: + status = TransactionStatusEnum.FAILED_ROLLBACK; + break; + default: + break; + } + + } + + private boolean isLastActionAlreadyCalled() { + return lastActionAlreadyCalled; + } + + private void setLastActionAlreadyCalled(boolean lastAction) { + this.lastActionAlreadyCalled = lastAction; + } + + // TODO test using slf4j-test and remove this + static void setLog(Logger log) { + TransactionSdncImpl.log = log; + } + + TransactionStatusEnum getStatus() { + return status; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java new file mode 100644 index 0000000000..56527b6e9b --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.config; + +import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; +import org.openecomp.sdc.common.transaction.mngr.TransactionManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan({"org.openecomp.sdc.be.user", + "org.openecomp.sdc.be.impl", + "org.openecomp.sdc.be.auditing.impl", + "org.openecomp.sdc.be.distribution", + "org.openecomp.sdc.be.switchover.detector", + "org.openecomp.sdc.be.tosca", + "org.openecomp.sdc.be.components.validation", + "org.openecomp.sdc.be.components.impl", + "org.openecomp.sdc.be.components.path", + "org.openecomp.sdc.be.components.merge", + "org.openecomp.sdc.be.components.csar", + "org.openecomp.sdc.be.components.property" +}) +public class CatalogBESpringConfig { + @Bean(name = "lifecycleBusinessLogic") + public LifecycleBusinessLogic lifecycleBusinessLogic() { + return new LifecycleBusinessLogic(); + } + + @Bean(name = "transactionManager") + public TransactionManager transactionManager() { + return new TransactionManager(); + } + + @Bean(name = "asset-metadata-utils") + public AssetMetadataConverter assetMetadataConverter() { + return new AssetMetadataConverter(); + } + +} diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml index 2b3603ce3b..b34ad69ffb 100644 --- a/catalog-be/src/main/resources/application-context.xml +++ b/catalog-be/src/main/resources/application-context.xml @@ -11,56 +11,18 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + base-package= "org.openecomp.sdc.be.components.health, + org.openecomp.sdc.be.servlets, + org.openecomp.sdc.be.externalapi.servlet, + org.openecomp.sdc.be.components.scheduledtasks, + org.openecomp.sdc.be.model.jsontitan.utils"> + + + + + diff --git a/catalog-be/src/main/resources/config/DME2preferredRouter.txt b/catalog-be/src/main/resources/config/DME2preferredRouter.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml index 190153cb0a..aefdacea98 100644 --- a/catalog-be/src/main/resources/config/configuration.yaml +++ b/catalog-be/src/main/resources/config/configuration.yaml @@ -23,7 +23,7 @@ beSslPort: 8443 version: 1.1.0 released: 2012-11-30 -toscaConformanceLevel: 5.0 +toscaConformanceLevel: 7.0 minToscaConformanceLevel: 3.0 titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties @@ -146,6 +146,7 @@ resourceTypes: &allResourceTypes - CP - VL - VF + - CR - VFCMT - Abstract - CVFC @@ -198,7 +199,8 @@ toscaArtifacts: excludeResourceCategory: - Generic excludeResourceType: - - PNF + - PNF + - CR informationalResourceArtifacts: features: displayName: Features @@ -422,7 +424,7 @@ resourceDeploymentArtifacts: DCAE_DOC: acceptedTypes: validForResourceTypes: - - VF + - VF - VFCMT DCAE_EVENT: acceptedTypes: @@ -532,6 +534,7 @@ resourceInformationalArtifacts: - CP - VL - VF + - CR - VFCMT - Abstract - PNF @@ -641,6 +644,7 @@ genericAssetNodeTypes: VFC: org.openecomp.resource.abstract.nodes.VFC CVFC: org.openecomp.resource.abstract.nodes.VFC VF : org.openecomp.resource.abstract.nodes.VF + CR : org.openecomp.resource.abstract.nodes.CR PNF: org.openecomp.resource.abstract.nodes.PNF Service: org.openecomp.resource.abstract.nodes.service @@ -662,3 +666,65 @@ environmentContext: - Needed_Non-Revenue - Useful_Non-Revenue - General_Non-Revenue + +dmaapConsumerConfiguration: + hosts: olsd004.wnsnet.attws.com:3905 + consumerGroup: asdc + consumerId: mama #mama - in Order To Consume Remove This String And Replace It With -> mama + timeoutMs: 15000 + limit: 1 + pollingInterval: 2 + topic: com.att.sdc.23911-SDCforTestDev-v001 + latitude: 32.109333 + longitude: 34.855499 + version: 1.0 + serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events + environment: TEST + partner: BOT_R + routeOffer: MR1 + protocol: https + contenttype: application/json + dme2TraceOn: true + aftEnvironment: AFTUAT + aftDme2ConnectionTimeoutMs: 15000 + aftDme2RoundtripTimeoutMs: 240000 + aftDme2ReadTimeoutMs: 50000 + dme2preferredRouterFilePath: DME2preferredRouter.txt + timeLimitForNotificationHandleMs: 120000 + credential: + username: m09875@sdc.att.com + password: hmXYcznAljMSisdy8zgcag== + + + +dmeConfiguration: + dme2Search: DME2SEARCH + dme2Resolve: DME2RESOLVE + + +excludedPolicyTypesMapping: + # VF: + # - a.b.c + # - c.d.e + #CR: + # - x.y.z + +excludedGroupTypesMapping: + CR: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root + VF: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root + Service: + - org.openecomp.groups.VfModule + - org.openecomp.groups.heat.HeatStack + - tosca.groups.Root + +healthStatusExclude: + - DE + - ES + - DMAAP + diff --git a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml index 60886cf40f..5ebbe82985 100644 --- a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml +++ b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml @@ -45,4 +45,41 @@ createTopic: startDistributionEngine: true -useHttpsWithDmaap: true \ No newline at end of file + +useHttpsWithDmaap: false +opEnvRecoveryIntervalSec: 180 +allowedTimeBeforeStaleSec: 300 + +aaiConfig: + httpRequestConfig: + serverRootUrl: https://aai-uint3.test.att.com:8443 + resourceNamespaces: + operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments + + httpClientConfig: + timeouts: + readTimeoutMs: 5000 + connectTimeoutMs: 1000 + clientCertificate: + keyStore: /opt/app/jetty/base/be/etc/non-prod.jks + keyStorePassword: hmXYcznAljMSisdy8zgcag== + headers: + X-FromAppId: asdc + numOfRetries: 3 + +msoConfig: + httpRequestConfig: + serverRootUrl: http://127.0.0.1:8080/onap/mso/infra/modelDistributions/v1 + resourceNamespaces: + distributions: /distributions + + httpClientConfig: + timeouts: + readTimeoutMs: 2000 + connectTimeoutMs: 500 + basicAuthorization: + userName: asdc + password: OTLEp5lfVhYdyw5EAtTUBQ== + numOfRetries: 3 + +currentArtifactInstallationTimeout: 120 diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index 9dc0355212..56d0e74b73 100644 --- a/catalog-be/src/main/resources/config/error-configuration.yaml +++ b/catalog-be/src/main/resources/config/error-configuration.yaml @@ -8,6 +8,10 @@ errors: code: 201, message: "OK" } + ACCEPTED: { + code: 202, + message: "Accepted" + } NO_CONTENT: { code: 204, message: "No Content" @@ -411,7 +415,6 @@ errors: message: "Error: Invalid Content. Missing Capability Type '%1'.", messageId: "SVC4115" } -#-----------SVC4116--------------------------- RESOURCE_INSTANCE_BAD_REQUEST: { code: 400, message: "Error: Invalid Content.", @@ -595,7 +598,7 @@ errors: } #---------SVC4301------------------------------ RESTRICTED_OPERATION: { - code: 409, + code: 403, message: "Error: Restricted operation.", messageId: "SVC4301" } @@ -1187,6 +1190,7 @@ errors: message: "Error: Invalid occurrences format.", messageId: "SVC4585" } +#---------SVC4586------------------------------ #---------SVC4586------------------------------ INVALID_SERVICE_API_URL: { code: 400, @@ -1658,7 +1662,7 @@ errors: # %1 - "groupName" INVALID_VF_MODULE_NAME: { code: 400, - message: "Error: Invalid Content. VF Module name '%1' contains invalid characters", + message: "Error: Invalid Content. Group name '%1' contains invalid characters", messageId: "SVC4646" } @@ -1877,4 +1881,154 @@ errors: code: 404, message: "Error: Requested relation %1 was not found on the container %2.", messageId: "SVC4674" - } \ No newline at end of file + } + + +#---------SVC4675------------------------------ + INVALID_SERVICE_STATE: { + code: 409, + message: "Service state is invalid for this action", + messageId: "SVC4675" + } + +#---------SVC4676------------------------------ + INVALID_RESPONSE_FROM_PROXY: { + code: 502, + message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server", + messageId: "SVC4676" + } + +#---------SVC4677------------------------------ + API_RESOURCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' was not found.", + messageId: "SVC4677" + } + +#---------SVC4678------------------------------ + BAD_REQUEST_MISSING_RESOURCE: { + code: 400, + message: "Error: The required resource name/id is missing in the request", + messageId: "SVC4678" + } +#---------SVC4679------------------------------ +# %1 forwarding path name maximum length + FORWARDING_PATH_NAME_MAXIMUM_LENGTH: { + code: 400, + message: "Forwarding path name too long, , maximum allowed 200 characters : '%1'.", + messageId: "SVC4679" + } +#---------SVC4680------------------------------ +# %1 Forwarding path name already in use + FORWARDING_PATH_NAME_ALREADY_IN_USE: { + code: 400, + message: "Forwarding path name already in use : '%1'.", + messageId: "SVC4680" + } +#---------SVC4681------------------------------ +# %1 Forwarding path name empty + FORWARDING_PATH_NAME_EMPTY: { + code: 400, + message: "Forwarding Path Name can't be empty .", + messageId: "SVC4681" + } +#---------SVC4682------------------------------ +# %1 - resource uniqueId +# %2 - resource component type + RESOURCE_CANNOT_CONTAIN_POLICIES: { + code: 400, + message: "Error: The resource %1 type of %2 cannot contain policies.", + messageId: "SVC4682" + } +#---------SVC4683------------------------------ +# %1 - policy uniqueId +# %2 - component uniqueId + POLICY_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested policy %1 was not found on the container %2.", + messageId: "SVC4683" +} +#---------SVC4684------------------------------ +# %1 - policy name + INVALID_POLICY_NAME: { + code: 400, + message: "Error: Invalid policy name %1 received.", + messageId: "SVC4684" + } +#---------SVC4685------------------------------ +# %1 - policy name + POLICY_NAME_ALREADY_EXIST: { + code: 409, + message: "Error: The policy with the name %1 already exists.", + messageId: "SVC4685" + } +#---------SVC4686------------------------------ +# %1 - policy name + POLICY_TARGET_DOES_NOT_EXIST: { + code: 400, + message: "Error: The targets %1 are not valid, all targets have to be on the topologyTemplate.", + messageId: "SVC4686" + } +#---------SVC4687------------------------------ +# %1 - policy type +# %2 - component type + EXCLUDED_POLICY_TYPE: { + code: 400, + message: "Error: The policy of the type %1 excluded to add to a component of the type %2.", + messageId: "SVC4687" + } + #---------SVC4688------------------------------ +# %1 - group type +# %2 - component type + GROUP_TYPE_ILLEGAL_PER_COMPONENT: { + code: 400, + message: "Error: group type %1 not permitted in component of type %2", + messageId: "SVC4688" + } + #---------SVC4689------------------------------ +# %1 - group type +# %2 - component type + POLICY_TARGET_TYPE_DOES_NOT_EXIST: { + code: 400, + message: "Error: The target types %1 are not valid.", + messageId: "SVC4689" + } + +#---------SVC4690------------------------------ +# %1 forwarding path protocol maximum length + FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH: { + code: 400, + message: "Forwarding path protocol too long, , maximum allowed 200 characters : '%1'.", + messageId: "SVC4690" + } + +#---------SVC4691------------------------------ +# %1 forwarding path destination port maximum length + FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH: { + code: 400, + message: "Forwarding path destination port too long, , maximum allowed 200 characters : '%1'.", + messageId: "SVC4691" + } + +#---------POL4692------------------------------ + MISSING_OLD_COMPONENT_INSTANCE: { + code: 400 , + message: "Error: Missing 'componentInstanceId' HTTP param.", + messageId: "POL4692" + } + +#---------POL4693------------------------------ + MISSING_NEW_COMPONENT_INSTANCE: { + code: 400 , + message: "Error: Missing 'newComponentInstanceId' HTTP param.", + messageId: "POL4693" + } + +#---------SVC4694------------------------------ +# %1 External Reference Value + EXT_REF_NOT_FOUND: { + code: 404, + message: "Error: External Reference '%1' was not found.", + messageId: "SVC4694" + } + diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml index ba16783536..b436f20c31 100644 --- a/catalog-be/src/main/resources/config/logback.xml +++ b/catalog-be/src/main/resources/config/logback.xml @@ -11,6 +11,8 @@ + + @@ -18,13 +20,11 @@ - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log - + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log - ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i - + ${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i 1 10 @@ -210,7 +210,7 @@ 20MB - ${default-log-pattern} + ${auditLoggerPattern} diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml index 4e25d735d0..50f74f8853 100644 --- a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml @@ -122,6 +122,8 @@ tosca.capabilities.Scalable: type: integer tosca.capabilities.network.Bindable: derived_from: tosca.capabilities.Node + + tosca.capabilities.Container.Docker: derived_from: tosca.capabilities.Container properties: @@ -207,6 +209,16 @@ org.openecomp.capabilities.metric.SnmpTrap: description: Object Id of the metric required: true status: SUPPORTED +org.openecomp.capabilities.Forwarder: + derived_from: tosca.capabilities.Root +org.openecomp.capabilities.VLANAssignment: + derived_from: tosca.capabilities.Root + description: ability to expose routing information of the internal network + properties: + vfc_instance_group_reference: + type: string + description: Ability to recognize capability per vfc instance group on vnf instance + required: true #ONAP types tosca.capabilities.nfv.VirtualStorage: derived_from: tosca.capabilities.Root diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip index 84871d6a07..6c443c9662 100644 Binary files a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip and b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml index 449842c2f4..493f399453 100644 --- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml @@ -1257,6 +1257,7 @@ org.openecomp.datatypes.flavors.DeploymentFlavor: license_flavor: type: org.openecomp.datatypes.flavors.LicenseFlavor required: false + org.openecomp.datatypes.ImageInfo: derived_from: tosca.datatypes.Root properties: @@ -1271,7 +1272,7 @@ org.openecomp.datatypes.ImageInfo: type: string required: false default: md5 -#onap +#ONAP types tosca.datatypes.nfv.VnfcConfigurableProperties: derived_from: tosca.datatypes.Root properties: diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip index 1f79bf2c2d..75f9f73a35 100644 Binary files a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip and b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml index ce457e4add..9711bfdebe 100644 --- a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml @@ -1,3 +1,8 @@ +tosca.groups.Root: + description: The TOSCA Group Type all other TOSCA Group Types derive from + interfaces: + Standard: + type: tosca.interfaces.node.lifecycle.Standard org.openecomp.groups.heat.HeatStack: derived_from: tosca.groups.Root description: Grouped all heat resources which are in the same heat stack @@ -77,9 +82,51 @@ org.openecomp.groups.VfModule: required: false description: > Identifies the set of VM types and their count included in the VF-Module -tosca.groups.Root: - description: The TOSCA Group Type all other TOSCA Group Types derive from - interfaces: - Standard: - type: tosca.interfaces.node.lifecycle.Standard - +org.openecomp.groups.NetworkCollection: + derived_from: tosca.groups.Root + description: groups l3-networks in network collection + properties: + network_collection_type: + type: string + required: true + description: network collection type, defined with default value + default: l3-network + network_collection_subtype: + type: string + required: true + description: network collection subtype, defined with default value + default: sub-interface + network_collection_role: + type: string + required: true + description: network collection role + network_collection_description: + type: string + required: true + description: network collection description, free format text +org.openecomp.groups.VfcInstanceGroup: + derived_from: tosca.groups.Root + description: groups VFCs with same parent port role + properties: + vfc_instance_group_role: + type: string + required: true + description: role of this VFC group + vfc_parent_port_role: + type: string + required: true + description: common role of parent ports of VFCs in this group + network_collection_role: + type: string + required: true + description: network collection role assigned to this group + subinterface_role: + type: string + required: true + description: common role of subinterfaces of VFCs in this group, criteria the group is created + capabilities: + vlan_assignment: + type: org.openecomp.capabilities.VLANAssignment + properties: + vfc_instance_group_reference: + type: string \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip index 7acd7a6b45..71a4af957a 100644 Binary files a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip and b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json new file mode 100644 index 0000000000..4245f4dab1 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json @@ -0,0 +1,21 @@ +{ + "payloadName": "Generic_CR.yml", + "contactId": "jh0003", + "name": "Generic_CR", + "description": "Represents a generic CR.", + "resourceIconPath": "defaulticon", + "resourceType": "ABSTRACT", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } +], + "tags": [ + "Generic_CR" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml new file mode 100644 index 0000000000..941bc451da --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml @@ -0,0 +1,15 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.resource.abstract.nodes.CR: + derived_from: tosca.nodes.Root + properties: + nf_function: + type: string + nf_role: + type: string + nf_naming_code: + type: string + nf_type: + type: string + nf_naming: + type: org.openecomp.datatypes.Naming diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip new file mode 100644 index 0000000000..5ea130c95e Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip index 85adfbc2a1..d20e69e8d6 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip index f69e5b40fb..48ebb1f610 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json new file mode 100644 index 0000000000..5b426db133 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json @@ -0,0 +1,21 @@ +{ + "payloadName": "forwardingPath.yml", + "contactId": "jh0003", + "name": "Forwarding Path", + "description": "Forwarding Path configuration object", + "resourceIconPath": "defaulticon", + "resourceType": "ABSTRACT", + "categories": [ + { + "name": "Generic", + "subcategories": [ + { + "name": "Abstract" + } + ] + } + ], + "tags": [ + "Forwarding Path" + ] +} \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml new file mode 100644 index 0000000000..fe1be7f1f2 --- /dev/null +++ b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml @@ -0,0 +1,24 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +node_types: + org.openecomp.nodes.ForwardingPath: + derived_from: tosca.nodes.Root + properties: + target_range: + type: list + required: true + status: SUPPORTED + entry_schema: + description: Identifier of the reciever port of the VNF or the service + type: integer + protocol: + type: string + description: protocol type that runs on the link + required: true + status: SUPPORTED + requirements: + - forwarder: + capability: org.openecomp.capabilities.Forwarder + relationship: org.openecomp.relationships.ForwardsTo + occurrences: + - 0 + - UNBOUNDED \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip new file mode 100644 index 0000000000..7135677bf1 Binary files /dev/null and b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml index 89ee9f81f0..791a0b9a3b 100644 --- a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml +++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml @@ -73,6 +73,8 @@ node_types: occurrences: - 1 - UNBOUNDED + forwarder: + type: org.openecomp.capabilities.Forwarder network.outgoing.bytes: type: org.openecomp.capabilities.metric.Ceilometer description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer. diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip index 8a23aa77c2..efeafe824e 100644 Binary files a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip and b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml index ceb22da2af..57f4b45abe 100644 --- a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml @@ -13,7 +13,7 @@ tosca.policies.Performance: derived_from: tosca.policies.Root description: The TOSCA Policy Type definition that is used to declare performance requirements for TOSCA nodes or groups of nodes. org.openecomp.policies.placement.Antilocate: - derived_from: tosca.policy.placement + derived_from: tosca.policies.Placement description: My placement policy for separation based upon container type value properties: name: @@ -32,7 +32,7 @@ org.openecomp.policies.placement.Antilocate: - region - compute org.openecomp.policies.placement.Colocate: - derived_from: tosca.policy.placement + derived_from: tosca.policies.Placement description: Keep associated nodes (groups of nodes) based upon affinity value properties: name: @@ -51,7 +51,7 @@ org.openecomp.policies.placement.Colocate: - region - compute org.openecomp.policies.placement.valet.Diversity: - derived_from: tosca.policy.placement + derived_from: tosca.policies.Placement description: Valet Diversity properties: level: @@ -65,7 +65,7 @@ org.openecomp.policies.placement.valet.Diversity: - host - rack org.openecomp.policies.placement.valet.Exclusivity: - derived_from: tosca.policy.placement + derived_from: tosca.policies.Placement description: Valet Exclusivity properties: level: @@ -79,7 +79,7 @@ org.openecomp.policies.placement.valet.Exclusivity: - host - rack org.openecomp.policies.placement.valet.Affinity: - derived_from: tosca.policy.placement + derived_from: tosca.policies.Placement description: Valet Affinity properties: level: @@ -91,4 +91,27 @@ org.openecomp.policies.placement.valet.Affinity: constraints: - valid_values: - host - - rack \ No newline at end of file + - rack +org.openecomp.policies.scaling.Fixed: + derived_from: tosca.policies.Scaling + properties: + quantity: + description: the exact number of instances to keep up + type: integer + required: true +org.openecomp.policies.External: + derived_from: tosca.policies.Root + description: externally managed policy (for example, type="network assignment", source="Policy Manager", name="route target") + properties: + source: + type: string + description: The name of the server that exposes the policy with predefined type and name. + required: false + type: + type: string + description: The type (category) of the policy same as it is defined in the source. + required: false + name: + type: string + description: The name of the policy, that related to specific type, same as it is defined in the source. + required: false diff --git a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip index 5ed696e4a9..fbc09f2e0c 100644 Binary files a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip and b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip differ diff --git a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml index 5fb5390721..36325ba8e6 100644 --- a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml @@ -108,4 +108,7 @@ description: The relative location (e.g., path on the file system), which provides the root location to address an attached node. type: string status: SUPPORTED - required: false \ No newline at end of file + required: false + org.openecomp.relationships.ForwardsTo: + derived_from: tosca.relationships.Root + valid_target_types: [org.openecomp.capabilities.Forwarder] \ No newline at end of file diff --git a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip index dbb1ca02f2..d8eb62d4d3 100644 Binary files a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip and b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip differ diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py index aca21754e8..2f3237173c 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py @@ -6,24 +6,24 @@ import copy from importNormativeElements import createNormativeElement from importCommon import * -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +######################################################################################################################################################################################### +# # +# Import categoriy types # +# # +# activation : # +# python importCategoryTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importCategoryTypes.py [-f | --ifile= ] # +# # +######################################################################################################################################################################################### def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importCategories(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/categories", "categoryTypes", "categoriesZip") +def importCategories(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/categories", "categoryTypes", "categoriesZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -41,9 +41,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -59,14 +60,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importCategories(beHost, bePort, adminUser, True, "../../../import/tosca/categories/") + importCategories(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/categories/") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py index 5d7f5b7576..ef51a907d5 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py @@ -6,24 +6,24 @@ import copy from importNormativeElements import createNormativeElement from importCommon import * -################################################################################################################################################ -# # -# Import tosca data types # -# # -# activation : # -# python importDataTypes.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importDataTypes.py [-f | --ifile= ] # -# # -################################################################################################################################################ +##################################################################################################################################################################################### +# # +# Import tosca data types # +# # +# activation : # +# python importDataTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importDataTypes.py [-f | --ifile= ] # +# # +##################################################################################################################################################################################### def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http ] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importDataTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/datatypes", "dataTypes", "dataTypesZip") +def importDataTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/datatypes", "dataTypes", "dataTypesZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -41,9 +41,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -59,14 +60,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importDataTypes(beHost, bePort, adminUser, True, "../../../import/tosca/data-types/") + importDataTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/data-types/") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py index 2b6a5db6f8..9daa990fc5 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py @@ -6,24 +6,24 @@ import copy from importNormativeElements import createNormativeElement from importCommon import * -################################################################################################################################################ -# # -# Import tosca data types # -# # -# activation : # -# python importGroupTypes.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importGroupTypes.py [-f | --ifile= ] # -# # -################################################################################################################################################ +##################################################################################################################################################################################### +# # +# Import tosca data types # +# # +# activation : # +# python importGroupTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importGroupTypes.py [-f | --ifile= ] # +# # +##################################################################################################################################################################################### def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http ] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importGroupTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/grouptypes", "groupTypes", "groupTypesZip") +def importGroupTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/grouptypes", "groupTypes", "groupTypesZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -41,9 +41,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -59,14 +60,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importGroupTypes(beHost, bePort, adminUser, True, "../../../import/tosca/group-types/") + importGroupTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/group-types/") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py index 8b16a72ab3..4490fec61a 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py @@ -7,19 +7,19 @@ from importCommon import * from importNormativeTypes import * import importCommon -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +##################################################################################################################################################################################### +# # +# Import heat types # +# # +# activation : # +# python importHeatTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importHeatTypes.py [-f | --ifile= ] # +# # +##################################################################################################################################################################################### -def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion): +def importHeatTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion): heatTypes = [ "globalNetwork", "globalPort", @@ -38,6 +38,7 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion): "abstractSubstitute", "Generic_VFC", "Generic_VF", + "Generic_CR", "Generic_PNF", "Generic_Service", "contrailNetworkRules", @@ -57,7 +58,8 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion): "extCp2", "extNeutronCP", "extContrailCP", - "portMirroringByPolicy" + "portMirroringByPolicy", + "forwardingPath" ] responseCodes = [200, 201] @@ -67,7 +69,7 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion): results = [] for heatType in heatTypes: - result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, heatType, updateversion) results.append(result) if ( result[1] == None or result[1] not in responseCodes) : print "Failed creating heat type " + heatType + ". " + str(result[1]) @@ -81,9 +83,10 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' updateversion = 'true' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -99,17 +102,19 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-v", "--updateversion"): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - results = importHeatTypes(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) + results = importHeatTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) print "-----------------------------" for result in results: diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py b/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py index f35cc7bcee..7d0b7c526a 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py @@ -16,7 +16,7 @@ def createZipFromYml(ymlFile, zipFile): zip.write(ymlFile, os.path.basename(ymlFile)) zip.close() -def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME): +def createUserNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME): try: log("in create normative type ", ELEMENT_NAME) @@ -26,7 +26,7 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME): buffer = StringIO() c = pycurl.Curl() - url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart' + url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart' c.setopt(c.URL, url) c.setopt(c.POST, 1) @@ -55,6 +55,9 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME): c.setopt(pycurl.HTTPPOST, send) c.setopt(c.WRITEFUNCTION, buffer.write) + if scheme == 'https': + c.setopt(c.SSL_VERIFYPEER, 0) + res = c.perform() #print("Before get response code") @@ -73,7 +76,7 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME): def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-l | --location=] [-e | --element=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-l | --location=] [-e | --element=]' print "----------------- Example -------------------" print "python importNodeType.py -d false -l /home/vagrant/catalog-be-1604.0.2.15.6-SNAPSHOT/scripts/import/tosca/../../../import/tosca/user-normative-types/ -e root1" @@ -86,9 +89,10 @@ def main(argv): debugf = None location = None element = None + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h",["ip=","port=","user=","location=","element=", "debug="]) + opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h:s:",["ip=","port=","user=","location=","element=", "debug=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -108,11 +112,13 @@ def main(argv): location = arg elif opt in ("-e", "--element"): element = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() @@ -139,7 +145,7 @@ def main(argv): #normativeType = "root1" - result = createUserNormativeType(beHost, bePort, adminUser, location, element) + result = createUserNormativeType(scheme, beHost, bePort, adminUser, location, element) #result = createUserNormativeType(beHost, bePort, adminUser, fileDir, normativeType) print "---------------------------------------" print "{0:30} | {1:6}".format(result[0], result[1]) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py index b6e390992e..d57c3d6ce4 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py @@ -18,21 +18,21 @@ from importPolicyTypes import importPolicyTypes from importCommon import * import importCommon -################################################################################################################################################################################################# -# # -# Import all users from a given file # -# # -# activation : # -# python importNormativeAll.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # -# [-v | --updateversion=] # -# # -# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # -# python importNormativeAll.py # -# # -################################################################################################################################################################################################# +################################################################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeAll.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# [-v | --updateversion=] # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # +# python importNormativeAll.py # +# # +################################################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' def handleResults(results, updateversion): printFrameLine() @@ -57,10 +57,11 @@ def main(argv): adminUser = 'jh0003' debugf = None updateversion = 'true' - importCommon.debugFlag = False + importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -76,6 +77,8 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") @@ -84,7 +87,7 @@ def main(argv): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -101,33 +104,33 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "data-types/" - importDataTypes(beHost, bePort, adminUser, False, fileLocation) + importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation) print 'sleep until data type cache is updated' time.sleep( 70 ) fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "interface-lifecycle-types/" - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "categories/" - importCategories(beHost, bePort, adminUser, False, fileLocation) + importCategories(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "normative-types/" - results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion) + results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(results, updateversion) fileLocation = baseFileLocation + "heat-types/" - resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, updateversion) fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) + importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation) errorAndExit(0, None) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py index bda02ddda9..e4f92139c2 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py @@ -7,25 +7,25 @@ from importNormativeElements import createNormativeElement from importCommon import * import importCommon -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +################################################################################################################################################################################################# +# # +# Import normative capabilities # +# # +# activation : # +# python importNormativeCapabilities.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importNormativeCapabilities.py [-f | --ifile= ] # +# # +################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importNormativeCapabilities(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/capability", "capabilityTypes", "capabilityTypeZip") +def importNormativeCapabilities(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/capability", "capabilityTypes", "capabilityTypeZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -44,9 +44,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="]) except getopt.GetoptError: usage() importCommon.errorAndExit(2, 'Invalid input') @@ -62,14 +63,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importNormativeCapabilities(beHost, bePort, adminUser, True, "../../../import/tosca/capability-types/") + importNormativeCapabilities(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/capability-types/") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py index af643da4f4..c28bbfb143 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py @@ -4,19 +4,19 @@ from StringIO import StringIO import json import copy from importCommon import * -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importUsers.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsers.py [-f | --ifile= ] # +# # +################################################################################################################################################################################# -def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMENT_NAME, elementFormName): +def createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, urlSuffix, ELEMENT_NAME, elementFormName): try: log("in create normative element ", ELEMENT_NAME) @@ -24,7 +24,7 @@ def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMEN buffer = StringIO() c = pycurl.Curl() - url = 'http://' + beHost + ':' + bePort + urlSuffix + url = scheme + '://' + beHost + ':' + bePort + urlSuffix c.setopt(c.URL, url) c.setopt(c.POST, 1) @@ -45,6 +45,10 @@ def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMEN #c.setopt(c.WRITEFUNCTION, lambda x: None) c.setopt(c.WRITEFUNCTION, buffer.write) + + if scheme == 'https': + c.setopt(c.SSL_VERIFYPEER, 0) + #print("before perform") res = c.perform() diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py index 33f1cc42de..a6ab5741e4 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py @@ -6,24 +6,24 @@ import copy from importNormativeElements import createNormativeElement from importCommon import * -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +############################################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeInterfaceLifecycleTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importNormativeInterfaceLifecycleTypes.py [-f | --ifile= ] # +# # +############################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle", "interfaceLifecycleTypes", "interfaceLifecycleTypeZip") +def importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle", "interfaceLifecycleTypes", "interfaceLifecycleTypeZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -42,9 +42,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -60,14 +61,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, True, "../../../import/tosca/interface-lifecycle-types//") + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/interface-lifecycle-types//") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py index 64a639c3c8..1061df862c 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py @@ -17,21 +17,21 @@ from importPolicyTypes import importPolicyTypes from importCommon import * import importCommon -################################################################################################################################################################################################# -# # -# Import all users from a given file # -# # -# activation : # -# python importNormativeAll.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # -# [-v | --updateversion=] # -# # -# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # -# python importNormativeAll.py # -# # -################################################################################################################################################################################################# +##################################################################################################################################################################################################################################################### +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeNoHeatAndNormativeTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# [-v | --updateversion=] # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # +# python importNormativeNoHeatAndNormativeTypes.py # +# # +##################################################################################################################################################################################################################################################### def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' def handleResults(results, updateversion): printFrameLine() @@ -57,9 +57,10 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=", "scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -75,6 +76,8 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") @@ -83,7 +86,7 @@ def main(argv): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -100,16 +103,16 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "data-types/" - importDataTypes(beHost, bePort, adminUser, False, fileLocation) + importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation) print 'sleep until data type cache is updated' time.sleep( 70 ) fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "interface-lifecycle-types/" - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation) #fileLocation = baseFileLocation + "categories/" #importCategories(beHost, bePort, adminUser, False, fileLocation) @@ -123,10 +126,10 @@ def main(argv): #handleResults(resultsHeat, updateversion) fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) + importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation) errorAndExit(0, None) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py index 1f523858b6..df2cd49687 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py @@ -5,19 +5,19 @@ import json import copy from importCommon import * import importCommon -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# [-v | --updateversion=] # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ - -def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion): +######################################################################################################################################################################################### +# # +# Import all users from a given file # +# # +# activation : # +# python importNormativeTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# [-v | --updateversion=] # +# shortest activation (be host = localhost, be port = 8080): # +# python importNormativeTypes.py [-f | --ifile= ] # +# # +######################################################################################################################################################################################### + +def createNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion): try: log("in create normative type ", ELEMENT_NAME) @@ -27,7 +27,7 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update buffer = StringIO() c = pycurl.Curl() - url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart' + url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart' if updateversion != None: url += '?createNewVersion=' + updateversion c.setopt(c.URL, url) @@ -58,6 +58,9 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update #data = json.dumps(user) #c.setopt(c.POSTFIELDS, data) + if scheme == 'https': + c.setopt(c.SSL_VERIFYPEER, 0) + #c.setopt(c.WRITEFUNCTION, lambda x: None) c.setopt(c.WRITEFUNCTION, buffer.write) #print("before perform") @@ -79,10 +82,10 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-v | --updateversion=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-v | --updateversion=]' -def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion): +def importNormativeTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion): normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network", "allottedResource"] #normativeTypes = [ "root" ] @@ -93,7 +96,7 @@ def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion): results = [] for normativeType in normativeTypes: - result = createNormativeType(beHost, bePort, adminUser, fileDir, normativeType, updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, normativeType, updateversion) results.append(result) if ( result[1] == None or result[1] not in responseCodes ): print "Failed creating normative type " + normativeType + ". " + str(result[1]) @@ -107,9 +110,10 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' updateversion = 'true' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -125,17 +129,19 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-v", "--updateversion"): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion if ( beHost == None ): usage() sys.exit(3) - results = importNormativeTypes(beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion) + results = importNormativeTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion) print "-----------------------------" for result in results: diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py b/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py index 3d7d9a9bbf..eb55bf84bc 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py @@ -23,7 +23,7 @@ import importCommon # Import all users from a given file # # # # activation : # -# python importNormativeAll.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# python importNormativeAll.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # # [-v | --updateversion=] # # # # shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # @@ -32,7 +32,7 @@ import importCommon ################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + print sys.argv[0], '[-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' def handleResults(results, updateversion): printFrameLine() @@ -58,6 +58,7 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) @@ -76,6 +77,8 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") @@ -84,7 +87,7 @@ def main(argv): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -101,37 +104,37 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "data-types/" - importDataTypes(beHost, bePort, adminUser, False, fileLocation) + importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation) print 'sleep until data type cache is updated' time.sleep( 70 ) fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "interface-lifecycle-types/" - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "categories/" - importCategories(beHost, bePort, adminUser, False, fileLocation) + importCategories(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "normative-types/" - results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion) + results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(results, updateversion) fileLocation = baseFileLocation + "heat-types/" - resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, updateversion) fileLocation = baseFileLocation + "onap-types/" - resultsHeat = importOnapTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = importOnapTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, updateversion) fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) + importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation) errorAndExit(0, None) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py index 18d2270442..faad226d39 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py @@ -7,19 +7,19 @@ from importCommon import * from importNormativeTypes import * import importCommon -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +##################################################################################################################################################################################################### +# # +# Import all users from a given file # +# # +# activation : # +# python importUsers.py [optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsers.py [-f | --ifile= ] # +# # +##################################################################################################################################################################################################### -def importOnapTypes(beHost, bePort, adminUser, fileDir, updateversion): +def importOnapTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion): onapTypes = [ "extImageFile", "extLocalStorage", @@ -41,7 +41,7 @@ def importOnapTypes(beHost, bePort, adminUser, fileDir, updateversion): results = [] for onapType in onapTypes: - result = createNormativeType(beHost, bePort, adminUser, fileDir, onapType, updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, onapType, updateversion) results.append(result) if ( result[1] == None or result[1] not in responseCodes) : print "Failed creating heat type " + onapType + ". " + str(result[1]) @@ -55,6 +55,7 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' updateversion = 'true' + scheme = 'http' try: opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) @@ -73,17 +74,19 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-v", "--updateversion"): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - results = importOnapTypes(beHost, bePort, adminUser, "../../../import/tosca/onap-types/", updateversion) + results = importOnapTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/onap-types/", updateversion) print "-----------------------------" for result in results: @@ -104,5 +107,3 @@ def main(argv): if __name__ == "__main__": main(sys.argv[1:]) - - diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py index c01e159264..103ad2d1da 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py @@ -6,24 +6,24 @@ import copy from importNormativeElements import createNormativeElement from importCommon import * -################################################################################################################################################ -# # -# Import tosca data types # -# # -# activation : # -# python importPolicyTypes.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importPolicyTypes.py [-f | --ifile= ] # -# # -################################################################################################################################################ +##################################################################################################################################################################################### +# # +# Import tosca data types # +# # +# activation : # +# python importPolicyTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importPolicyTypes.py [-f | --ifile= ] # +# # +##################################################################################################################################################################################### def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ]' -def importPolicyTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir): - result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/policytypes", "policyTypes", "policyTypesZip") +def importPolicyTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir): + result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/policytypes", "policyTypes", "policyTypesZip") printFrameLine() printNameAndReturnCode(result[0], result[1]) @@ -41,9 +41,10 @@ def main(argv): beHost = 'localhost' bePort = '8080' adminUser = 'jh0003' + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="]) + opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=", "scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -59,14 +60,16 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - importPolicyTypes(beHost, bePort, adminUser, True, "../../../import/tosca/policy-types/") + importPolicyTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/policy-types/") if __name__ == "__main__": diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py b/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py index 8509855f38..8e69ffcf49 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py @@ -5,22 +5,22 @@ import json import copy import yaml -######################################################################################################################################################## -# # -# Import all users from a given YAML file # -# # -# activation : # -# python importUsersFromYaml.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # # -# python importUsersFromYaml.py [-f | --ifile= ] # -# # -# PyYAML module shall be added to python. # -# pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080 # -######################################################################################################################################################## - - -def importUsers(beHost, bePort, users, adminUser): +######################################################################################################################################################################################### +# # +# Import all users from a given YAML file # +# # +# activation : # +# python importUsersFromYaml.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsersFromYaml.py [-f | --ifile= ] # +# # +# PyYAML module shall be added to python. # +# pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080 # +######################################################################################################################################################################################### + + +def importUsers(scheme, beHost, bePort, users, adminUser): result = [] @@ -28,12 +28,12 @@ def importUsers(beHost, bePort, users, adminUser): #print("Going to add user " + user['userId']) - getRes = getUser(beHost, bePort, user) + getRes = getUser(scheme, beHost, bePort, user) userId = getRes[0] error = getRes[1] #print error if ( error != None and error == 404 ): - res = createUser(beHost, bePort, user ,adminUser) + res = createUser(scheme, beHost, bePort, user ,adminUser) result.append(res) else: if ( error == 200 ): @@ -45,7 +45,7 @@ def importUsers(beHost, bePort, users, adminUser): return result -def getUser(beHost, bePort, user): +def getUser(scheme, beHost, bePort, user): if (user.get('userId') == None): print "Ignoring record", user @@ -56,9 +56,12 @@ def getUser(beHost, bePort, user): c = pycurl.Curl() #print type(userId) - url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId) + url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId) c.setopt(c.URL, url) + if scheme == 'https': + c.setopt(c.SSL_VERIFYPEER, 0) + #adminHeader = 'USER_ID: ' + adminUser c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']) c.setopt(c.WRITEFUNCTION, lambda x: None) @@ -81,7 +84,7 @@ def getUser(beHost, bePort, user): -def createUser(beHost, bePort, user, adminUser): +def createUser(scheme, beHost, bePort, user, adminUser): if (user.get('userId') == None): print "Ignoring record", user @@ -92,7 +95,7 @@ def createUser(beHost, bePort, user, adminUser): buffer = StringIO() c = pycurl.Curl() - url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user' + url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user' c.setopt(c.URL, url) c.setopt(c.POST, 1) @@ -100,7 +103,10 @@ def createUser(beHost, bePort, user, adminUser): c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader]) data = json.dumps(user) - c.setopt(c.POSTFIELDS, data) + c.setopt(c.POSTFIELDS, data) + + if scheme == 'https': + c.setopt(c.SSL_VERIFYPEER, 0) c.setopt(c.WRITEFUNCTION, lambda x: None) #print("before perform") @@ -131,7 +137,7 @@ def errorAndExit(errorCode, errorDesc): sys.exit(errorCode) def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-f | --ifile= ]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-f | --ifile= ]' def main(argv): print 'Number of arguments:', len(sys.argv), 'arguments.' @@ -141,9 +147,10 @@ def main(argv): inputfile = None adminUser = 'jh0003' + scheme ='http' try: - opts, args = getopt.getopt(argv,"i:p:f:h:",["ip=","port=","ifile="]) + opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -159,8 +166,10 @@ def main(argv): bePort = arg elif opt in ("-f", "--ifile"): inputfile = arg + elif opt in ("-s", "--scheme"): + scheme = arg - print 'be host =',beHost,', be port =', bePort,', users file =',inputfile + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile if ( inputfile == None ): usage() @@ -187,7 +196,7 @@ def main(argv): #activeUsers = filter(lambda x: x.get('status') == None or x['status'] == 'ACTIVE', cloneUsers) - resultTable = importUsers(beHost, bePort, cloneUsers, adminUser) + resultTable = importUsers(scheme, beHost, bePort, cloneUsers, adminUser) g = lambda x: x[1] != 201 and x[1] != 409 diff --git a/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json b/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json index d239a15c72..7ea3dd4eda 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json +++ b/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json @@ -1,19 +1,6 @@ { "heat": [ - "contrailPort", - "extCp", - "contrailV2VirtualMachineInterface", - "neutronPort", - "Generic_PNF", - "portMirroring", - "Generic_VF", - "serviceProxy", - "extCp2", - "extContrailCP", - "vnfConfiguration", - "extVl", - "multiFlavorVFC", - "portMirroringByPolicy" + "Generic_CR" ], "normative": [ ] diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py index e35e2d28eb..5a1d1046b9 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py @@ -9,18 +9,18 @@ import importCommon import json -################################################################################################################################################ -# # -# Upgrades all Heat and Normative types confiugred in "typesToUpgrade.json" file # -# # -# activation : # -# python upgradeHeatAndNormativeTypes.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # -# python upgradeHeatAndNormativeTypes.py [-f | --ifile= ] # -# # -################################################################################################################################################ -def upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseDir, updateversion): +################################################################################################################################################################################################ +# # +# Upgrades all Heat and Normative types confiugred in "typesToUpgrade.json" file # +# # +# activation # +# python upgradeHeatAndNormativeTypes.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python upgradeHeatAndNormativeTypes.py [-f | --ifile= ] # +# # +################################################################################################################################################################################################ +def upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseDir, updateversion): responseCodes = [200, 201] if (updateversion == 'false'): responseCodes = [200, 201, 409] @@ -37,12 +37,12 @@ def upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseDir, updateversion) debug(normativeFileDir) results = [] for heatType in heatTypes: - result = createNormativeType(beHost, bePort, adminUser, heatFileDir, heatType.encode('ascii', 'ignore'), updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, heatFileDir, heatType.encode('ascii', 'ignore'), updateversion) results.append(result) if (result[1] == None or result[1] not in responseCodes): print "Failed creating heat type " + heatType + ". " + str(result[1]) for normativeType in normativeTypes: - result = createNormativeType(beHost, bePort, adminUser, normativeFileDir, normativeType.encode('ascii', 'ignore'), updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, normativeFileDir, normativeType.encode('ascii', 'ignore'), updateversion) results.append(result) if (result[1] == None or result[1] not in responseCodes): print "Failed creating normative type " + normativeType + ". " + str(result[1]) @@ -59,9 +59,10 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' updateversion = 'true' + scheme = 'http' try: - opts, args = getopt.getopt(argv, "i:p:u:v:h:", ["ip=", "port=", "user=", "updateversion="]) + opts, args = getopt.getopt(argv, "i:p:u:v:h:s:", ["ip=", "port=", "user=", "updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -77,17 +78,19 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-v", "--updateversion"): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =', beHost, ', be port =', bePort, ', user =', adminUser + print 'scheme =',scheme,', be host =',beHost, ', be port =', bePort, ', user =', adminUser if (beHost == None): usage() sys.exit(3) - results = upgradeTypesPerConfigFile(beHost, bePort, adminUser, "../../../import/tosca/", updateversion) + results = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, "../../../import/tosca/", updateversion) print "-----------------------------" for result in results: diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py index 7315ec0635..5cb0ca3b0c 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py @@ -7,19 +7,19 @@ from importCommon import * from importNormativeTypes import * import importCommon -################################################################################################################################################ -# # -# Import all users from a given file # -# # -# activation : # -# python importUsers.py [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # -# # -# shortest activation (be host = localhost, be port = 8080): # -# python importUsers.py [-f | --ifile= ] # -# # -################################################################################################################################################ +################################################################################################################################################################################# +# # +# Import all users from a given file # +# # +# activation : # +# python importUsers.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-f | --ifile= ] # +# # +# shortest activation (be host = localhost, be port = 8080): # +# python importUsers.py [-f | --ifile= ] # +# # +################################################################################################################################################################################# -def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion): +def upgradeHeatTypes1707(scheme, beHost, bePort, adminUser, fileDir, updateversion): heatTypes = [ "volume", "cinderVolume", @@ -49,7 +49,7 @@ def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion): results = [] for heatType in heatTypes: - result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, heatType, updateversion) results.append(result) if ( result[1] == None or result[1] not in responseCodes) : print "Failed creating heat type " + heatType + ". " + str(result[1]) @@ -63,9 +63,10 @@ def main(argv): bePort = '8080' adminUser = 'jh0003' updateversion = 'true' - + scheme = 'http' + try: - opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -81,17 +82,19 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-v", "--updateversion"): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser if ( beHost == None ): usage() sys.exit(3) - results = upgradeHeatTypes1707(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) + results = upgradeHeatTypes1707(scheme, beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion) print "-----------------------------" for result in results: diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py index 69a51f41f1..573e05b46a 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py @@ -17,21 +17,21 @@ from importOnapTypes import importOnapTypes from importCommon import * import importCommon -################################################################################################################################################################################################# -# # -# Upgrades the normative types # -# # -# activation : # -# python upgradeNormative.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # -# # -# # -# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # -# python upgradeNormative.py # -# # -################################################################################################################################################################################################# +################################################################################################################################################################################################################################# +# # +# Upgrades the normative types # +# # +# activation : # +# python upgradeNormative.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # +# python upgradeNormative.py # +# # +################################################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' def handleResults(results, updateversion): printFrameLine() @@ -52,9 +52,10 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="]) + opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -70,11 +71,13 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -91,27 +94,27 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "categories/" - importCategories(beHost, bePort, adminUser, False, fileLocation) + importCategories(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "data-types/" - importDataTypes(beHost, bePort, adminUser, False, fileLocation) + importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) - - fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation) + + fileLocation = baseFileLocation + "group-types/" + importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "interface-lifecycle-types/" - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation) print 'sleep until data type cache is updated' time.sleep( 70 ) - resultsHeat = upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseFileLocation, updateversion) + resultsHeat = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseFileLocation, updateversion) handleResults(resultsHeat, 'false') errorAndExit(0, None) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py index 8f8e0491ae..958416da33 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py @@ -7,21 +7,21 @@ from importCommon import * from importNormativeTypes import createNormativeType import importCommon -################################################################################################################################################################################################# -# # -# Upgrades the normative types # -# # -# activation : # -# python upgradeNormative.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # -# # -# # -# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # -# python upgradeNormative.py # -# # -################################################################################################################################################################################################# +################################################################################################################################################################################################################################# +# # +# Upgrades the normative types # +# # +# activation : # +# python upgradeNormative.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # +# python upgradeNormative.py # +# # +################################################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' def handleResults(results, updateversion): printFrameLine() @@ -41,10 +41,11 @@ def main(argv): adminUser = 'jh0003' debugf = None updateversion = 'true' - importCommon.debugFlag = False + importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="]) + opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -60,11 +61,13 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -87,11 +90,11 @@ def main(argv): ########################################################################## fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) results.append(result) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py index d45b27e755..805d012298 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py @@ -10,7 +10,7 @@ from importCommon import * import importCommon def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] [-v | --updateversion=]' def handleResults(results, updateversion): printFrameLine() @@ -36,9 +36,10 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="]) + opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -54,6 +55,8 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") @@ -62,7 +65,7 @@ def main(argv): if (arg.lower() == "false" or arg.lower() == "no"): updateversion = 'false' - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -79,11 +82,11 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "normative-types/" - results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion) + results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(results, updateversion) fileLocation = baseFileLocation + "heat-types/" - resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, updateversion) fileLocation = baseFileLocation + "onap-types/" diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py index 13e5d7d63a..c75966cfc9 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py @@ -7,21 +7,21 @@ from importCommon import * from importNormativeTypes import createNormativeType import importCommon -################################################################################################################################################################################################# -# # -# Upgrades the normative types # -# # -# activation : # -# python upgradeNormative.py [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # -# # -# # -# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # # -# python upgradeNormative.py # -# # -################################################################################################################################################################################################# +################################################################################################################################################################################################################################# +# # +# Upgrades the normative types # +# # +# activation : # +# python upgradeNormative.py [-s | --scheme= ] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=] # +# # +# # +# shortest activation (be host = localhost, be port = 8080, user = jh0003): # +# python upgradeNormative.py # +# # +################################################################################################################################################################################################################################# def usage(): - print sys.argv[0], '[-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' + print sys.argv[0], '[optional -s | --scheme=, default http] [-i | --ip=] [-p | --port= ] [-u | --user= ] [-d | --debug=]' def handleResults(results, updateversion): printFrameLine() @@ -42,9 +42,10 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: - opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="]) + opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="]) except getopt.GetoptError: usage() errorAndExit(2, 'Invalid input') @@ -60,11 +61,13 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf + print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -88,35 +91,35 @@ def main(argv): fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "novaServer", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion) results.append(result) fileLocation = baseFileLocation + "heat-types/" - result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion) + result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion) results.append(result) diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py index 4d0ec291f5..b272c2726c 100644 --- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py +++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py @@ -52,6 +52,7 @@ def main(argv): debugf = None updateversion = 'true' importCommon.debugFlag = False + scheme = 'http' try: opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="]) @@ -70,11 +71,13 @@ def main(argv): bePort = arg elif opt in ("-u", "--user"): adminUser = arg + elif opt in ("-s", "--scheme"): + scheme = arg elif opt in ("-d", "--debug"): print arg debugf = bool(arg.lower() == "true" or arg.lower() == "yes") - print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf + print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf if (debugf != None): print 'set debug mode to ' + str(debugf) @@ -91,31 +94,31 @@ def main(argv): baseFileLocation = pathdir + "/../../../import/tosca/" fileLocation = baseFileLocation + "categories/" - importCategories(beHost, bePort, adminUser, False, fileLocation) + importCategories(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "data-types/" - importDataTypes(beHost, bePort, adminUser, False, fileLocation) + importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "policy-types/" - importPolicyTypes(beHost, bePort, adminUser, False, fileLocation) + importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "group-types/" - importGroupTypes(beHost, bePort, adminUser, False, fileLocation) + importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "capability-types/" - importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation) + importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation) fileLocation = baseFileLocation + "interface-lifecycle-types/" - importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation) + importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation) print 'sleep until data type cache is updated' time.sleep( 70 ) - resultsHeat = upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseFileLocation, updateversion) + resultsHeat = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseFileLocation, updateversion) handleResults(resultsHeat, 'false') fileLocation = baseFileLocation + "onap-types/" - resultsHeat = importOnapTypes(beHost, bePort, adminUser, fileLocation, updateversion) + resultsHeat = importOnapTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion) handleResults(resultsHeat, updateversion) errorAndExit(0, None) diff --git a/catalog-be/src/main/webapp/WEB-INF/web.xml b/catalog-be/src/main/webapp/WEB-INF/web.xml index 70f5ff229c..b9fd99bd4b 100644 --- a/catalog-be/src/main/webapp/WEB-INF/web.xml +++ b/catalog-be/src/main/webapp/WEB-INF/web.xml @@ -12,10 +12,16 @@ jersey.config.server.provider.classnames - io.swagger.jersey.listing.ApiListingResourceJSON, - org.glassfish.jersey.media.multipart.MultiPartFeature, - org.openecomp.sdc.be.filters.BeServletFilter, - org.openecomp.sdc.be.filters.ComponentsAvailabilityFilter + io.swagger.jersey.listing.ApiListingResourceJSON, + org.glassfish.jersey.media.multipart.MultiPartFeature, + org.openecomp.sdc.be.filters.BeServletFilter, + org.openecomp.sdc.be.filters.ComponentsAvailabilityFilter, + org.openecomp.sdc.be.servlets.DefaultExceptionMapper, + org.openecomp.sdc.be.servlets.ComponentExceptionMapper, + org.openecomp.sdc.be.servlets.StorageExceptionMapper, + org.openecomp.sdc.be.view.MixinModelWriter + + swagger.scanner.id diff --git a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java deleted file mode 100644 index 272f0d6a1d..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc; - -import java.util.EnumMap; - -import org.openecomp.sdc.be.auditing.api.IAuditingManager; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AuditingMockManager implements IAuditingManager { - - private static Logger log = LoggerFactory.getLogger(AuditingMockManager.class.getName()); - - public AuditingMockManager(String string) { - // TODO Auto-generated constructor stub - } - - @Override - public void auditEvent(EnumMap auditingFields) { - AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - log.debug("call was made to auditEvent with event type {}", actionEnum.getName()); - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java index 45b2317cd6..2088e8071a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java @@ -20,10 +20,7 @@ package org.openecomp.sdc; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -38,228 +35,230 @@ import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.CategoryData; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; public class ElementOperationMock implements IElementOperation { - CategoryDefinition resourceCategory; - CategoryDefinition serviceCategory; - CategoryDefinition productCategory; - - Category oldService; - - public ElementOperationMock() { - resourceCategory = new CategoryDefinition(); - resourceCategory.setName("Network Layer 2-3"); - SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(); - subCategoryDefinition.setName("Router"); - SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition(); - subCategoryDefinition1.setName("Gateway"); - - resourceCategory.addSubCategory(subCategoryDefinition); - resourceCategory.addSubCategory(subCategoryDefinition1); - - serviceCategory = new CategoryDefinition(); - serviceCategory.setName("Mobility"); - oldService = new Category(); - oldService.setName("Mobility"); - - productCategory = new CategoryDefinition(); - productCategory.setName("Network Layer 2-31"); - SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition(); - subCategoryDefinition11.setName("Router1"); - GroupingDefinition group = new GroupingDefinition(); - group.setName("group1"); - subCategoryDefinition11.addGrouping(group); - productCategory.addSubCategory(subCategoryDefinition11); - - } - - @Override - public Either, ActionStatus> getAllResourceCategories() { - - List categories = new ArrayList(); - categories.add(resourceCategory); - return Either.left(categories); - - } - - @Override - public Either, ActionStatus> getAllServiceCategories() { - - List categories = new ArrayList(); - categories.add(serviceCategory); - return Either.left(categories); - - } - - /* - * @Override public Either getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } } - */ - - @Override - public Either, ActionStatus> getAllTags() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getAllPropertyScopes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getAllArtifactTypes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getAllDeploymentArtifactTypes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getCategoryData(String name, NodeTypeEnum type, Class clazz) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getDefaultHeatTimeout() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either deleteCategory(NodeTypeEnum nodeType, String categoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { - - List categories = new ArrayList(); - switch (nodeType) { - case ResourceNewCategory: - categories.add(resourceCategory); - break; - case ProductCategory: - categories.add(productCategory); - break; - case ServiceNewCategory: - categories.add(serviceCategory); - break; - default: - break; - } - return Either.left(categories); - } - - @Override - public Either getCategory(NodeTypeEnum nodeType, String categoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either deleteGrouping(NodeTypeEnum nodeType, String groupingId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getResourceTypesMap() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either getNewCategoryData(String name, NodeTypeEnum type, Class clazz) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either, ActionStatus> getAllProductCategories() { - List categories = new ArrayList(); - categories.add(productCategory); - return Either.left(categories); - } - - @Override - public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { - // TODO Auto-generated method stub - return null; - } + CategoryDefinition resourceCategory; + CategoryDefinition serviceCategory; + CategoryDefinition productCategory; + + Category oldService; + + public ElementOperationMock() { + resourceCategory = new CategoryDefinition(); + resourceCategory.setName("Network Layer 2-3"); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(); + subCategoryDefinition.setName("Router"); + SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition(); + subCategoryDefinition1.setName("Gateway"); + + resourceCategory.addSubCategory(subCategoryDefinition); + resourceCategory.addSubCategory(subCategoryDefinition1); + + serviceCategory = new CategoryDefinition(); + serviceCategory.setName("Mobility"); + oldService = new Category(); + oldService.setName("Mobility"); + + productCategory = new CategoryDefinition(); + productCategory.setName("Network Layer 2-31"); + SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition(); + subCategoryDefinition11.setName("Router1"); + GroupingDefinition group = new GroupingDefinition(); + group.setName("group1"); + subCategoryDefinition11.addGrouping(group); + productCategory.addSubCategory(subCategoryDefinition11); + + } + + @Override + public Either, ActionStatus> getAllResourceCategories() { + + List categories = new ArrayList(); + categories.add(resourceCategory); + return Either.left(categories); + + } + + @Override + public Either, ActionStatus> getAllServiceCategories() { + + List categories = new ArrayList(); + categories.add(serviceCategory); + return Either.left(categories); + + } + + /* + * @Override public Either getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } } + */ + + @Override + public Either, ActionStatus> getAllTags() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllPropertyScopes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllDeploymentArtifactTypes() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getCategoryData(String name, NodeTypeEnum type, Class clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getDefaultHeatTimeout() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { + + List categories = new ArrayList(); + switch (nodeType) { + case ResourceNewCategory: + categories.add(resourceCategory); + break; + case ProductCategory: + categories.add(productCategory); + break; + case ServiceNewCategory: + categories.add(serviceCategory); + break; + default: + break; + } + return Either.left(categories); + } + + @Override + public Either getCategory(NodeTypeEnum nodeType, String categoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either deleteGrouping(NodeTypeEnum nodeType, String groupingId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getResourceTypesMap() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either getNewCategoryData(String name, NodeTypeEnum type, Class clazz) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either, ActionStatus> getAllProductCategories() { + List categories = new ArrayList(); + categories.add(productCategory); + return Either.left(categories); + } + + @Override + public Either createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java index 5b86b9cc69..7f5b7f9853 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java @@ -20,10 +20,6 @@ package org.openecomp.sdc; -import static org.junit.Assert.assertTrue; - -import java.io.File; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.config.ErrorConfiguration; @@ -37,41 +33,45 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; + +import static org.junit.Assert.assertTrue; + public class ErrorConfigurationTest { - ConfigurationSource configurationSource = null; - private static Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class.getName()); + ConfigurationSource configurationSource = null; + private static final Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class); - @Before - public void setup() { + @Before + public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - } + } - @Test - public void testReadConfigurationFile() { + @Test + public void testReadConfigurationFile() { - ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { + ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() { - public void reconfigure(BasicConfiguration obj) { - // TODO Auto-generated method stub - log.debug("In reconfigure of {}", obj); - } + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub + log.debug("In reconfigure of {}", obj); + } - }); + }); - ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener); + ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener); - assertTrue(testConfiguration != null); - ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND"); - assertTrue(errorInfo != null); - log.debug("{}", testConfiguration); - log.debug("{}", errorInfo); + assertTrue(testConfiguration != null); + ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND"); + assertTrue(errorInfo != null); + log.debug("{}", testConfiguration); + log.debug("{}", errorInfo); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java index f9819c72e5..4698c0eea9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java @@ -20,8 +20,6 @@ package org.openecomp.sdc; -import java.io.IOException; - import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.common.api.BasicConfiguration; import org.openecomp.sdc.common.api.ConfigurationListener; @@ -31,32 +29,34 @@ import org.openecomp.sdc.common.impl.ConfigFileChangeListener; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.io.IOException; + public class TestExternalConfiguration { - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws IOException { - ExternalConfiguration.setAppName("catalog-server"); - ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config"); - ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppName("catalog-server"); + ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config"); + ExternalConfiguration.listenForChanges(); - ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() { + ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() { - @Override - public void reconfigure(BasicConfiguration obj) { - // TODO Auto-generated method stub + @Override + public void reconfigure(BasicConfiguration obj) { + // TODO Auto-generated method stub - } - }); + } + }); - ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); - configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); + ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir()); + configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener); - try { - Thread.currentThread().sleep(100 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + try { + Thread.currentThread().sleep(100 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java index c3f211f7ab..9ee123a840 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java @@ -20,6 +20,9 @@ package org.openecomp.sdc; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.ByteArrayOutputStream; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; @@ -30,100 +33,97 @@ import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.output.ByteArrayOutputStream; - public class ZipUtil { - public static void main(String[] args) { + public static void main(String[] args) { - String zipFileName = "/src/test/resources/config/config.zip"; + String zipFileName = "/src/test/resources/config/config.zip"; - zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip"; - zipFileName = "src/test/resources/config/config.zip"; + zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip"; + zipFileName = "src/test/resources/config/config.zip"; - Path path = Paths.get(zipFileName); + Path path = Paths.get(zipFileName); - try { - byte[] zipAsBytes = Files.readAllBytes(path); - // encode to base + try { + byte[] zipAsBytes = Files.readAllBytes(path); + // encode to base - byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); - String decodedStr = new String(decodedMd5); + byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes); + String decodedStr = new String(decodedMd5); - zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); + zipAsBytes = Base64.decodeBase64(decodedStr.getBytes()); - // String str = new String(zipAsBytes); + // String str = new String(zipAsBytes); - // readZip(str.getBytes()); - readZip(zipAsBytes); + // readZip(str.getBytes()); + readZip(zipAsBytes); - } catch (IOException e) { - e.printStackTrace(); - } + } catch (IOException e) { + e.printStackTrace(); + } - } + } - private static Map readZip(byte[] zipAsBytes) { + private static Map readZip(byte[] zipAsBytes) { - Map fileNameToByteArray = new HashMap(); + Map fileNameToByteArray = new HashMap(); - byte[] buffer = new byte[1024]; - ZipInputStream zis = null; - try { + byte[] buffer = new byte[1024]; + ZipInputStream zis = null; + try { - zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes)); - // get the zipped file list entry - ZipEntry ze = zis.getNextEntry(); + zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes)); + // get the zipped file list entry + ZipEntry ze = zis.getNextEntry(); - while (ze != null) { + while (ze != null) { - String fileName = ze.getName(); + String fileName = ze.getName(); - if (false == ze.isDirectory()) { + if (false == ze.isDirectory()) { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - int len; - while ((len = zis.read(buffer)) > 0) { - os.write(buffer, 0, len); - } + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + int len; + while ((len = zis.read(buffer)) > 0) { + os.write(buffer, 0, len); + } - // aClass.outputStreamMethod(os); - String aString = new String(os.toByteArray(), "UTF-8"); + // aClass.outputStreamMethod(os); + String aString = new String(os.toByteArray(), "UTF-8"); - fileNameToByteArray.put(fileName, os.toByteArray()); + fileNameToByteArray.put(fileName, os.toByteArray()); - } finally { - if (os != null) { - os.close(); - } - } - } - ze = zis.getNextEntry(); + } finally { + if (os != null) { + os.close(); + } + } + } + ze = zis.getNextEntry(); - } + } - zis.closeEntry(); - zis.close(); + zis.closeEntry(); + zis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - return null; - } finally { - if (zis != null) { - try { - zis.closeEntry(); - zis.close(); - } catch (IOException e) { - // TODO: add log - } + } catch (IOException ex) { + ex.printStackTrace(); + return null; + } finally { + if (zis != null) { + try { + zis.closeEntry(); + zis.close(); + } catch (IOException e) { + // TODO: add log + } - } - } + } + } - return fileNameToByteArray; + return fileNameToByteArray; - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java index a6c8dc4f0c..84c6fc118d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be; -import static org.mockito.Mockito.mock; - import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.common.api.ConfigurationListener; import org.openecomp.sdc.common.api.ConfigurationSource; +import static org.mockito.Mockito.mock; + public class DummyConfigurationManager { private DistributionEngineConfiguration distributionConfigurationMock = mock(DistributionEngineConfiguration.class); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java new file mode 100644 index 0000000000..9bdf784f1c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java @@ -0,0 +1,132 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.junit.Test; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.common.api.Constants; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; + +public class AuditBaseEventFactoryTest { + + private User user = new User(); + + @Test + public void buildUserNameWhenFullNameAndUserIdNotSet() { + assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsNotSetAndUserIdIsSet() { + user.setUserId(USER_ID); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsNullNullAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(Constants.NULL_STRING); + user.setLastName(Constants.NULL_STRING); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirtsNameIsNotSetAndLastNameIsNull() { + user.setUserId(USER_ID); + user.setLastName(Constants.NULL_STRING); + assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenLastNameIsNull() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(Constants.NULL_STRING); + assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirstNameIsNullAndLastNameIsSet() { + user.setUserId(USER_ID); + user.setFirstName(Constants.NULL_STRING); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_LAST_NAME + "(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFullNameIsSetAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_UID, AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildUserNameWhenFirstNameIsSetAndUserIdSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user)); + } + + @Test + public void buildExtendedUserNameWhenNothingIsSet() { + assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyUserIdIsSet() { + user.setUserId(USER_ID); + assertEquals(USER_ID, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameAllSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + user.setEmail(USER_EMAIL); + user.setRole(DESIGNER_USER_ROLE); + assertEquals(USER_EXTENDED_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenFirstNameAndUserIdAreSet() { + user.setUserId(USER_ID); + user.setFirstName(USER_FIRST_NAME); + assertEquals(USER_ID + ", " + USER_FIRST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenLastNameAndUserIdAreSet() { + user.setUserId(USER_ID); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_ID + ", " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyEmailAndRoleAreSet() { + user.setEmail(USER_EMAIL); + user.setRole(DESIGNER_USER_ROLE); + assertEquals(USER_EMAIL + ", " + DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyNameIsSet() { + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + assertEquals(USER_FIRST_NAME + " " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user)); + } + + @Test + public void buildExtendedUserNameWhenOnlyRoleIsSet() { + user.setRole(DESIGNER_USER_ROLE); + assertEquals(DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java new file mode 100644 index 0000000000..0a90ffd915 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java @@ -0,0 +1,200 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.ConsumerDefinition; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_PASSWORD; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_SALT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ECOMP_USER_CRED_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditConsumerEventFuncTest { + private AuditingManager auditingManager; + + private ConsumerDefinition consumer; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + consumer = new ConsumerDefinition(); + consumer.setConsumerName(USER_ID); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddEcompUserCredEvent() { + AuditEventFactory factory = new AuditConsumerEventFactory( + AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, consumer); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName()); + } + + @Test + public void testOldAddEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName()); + + } + + @Test + public void testNewGetEcompUserCredEvent() { + AuditEventFactory factory = new AuditConsumerEventFactory( + AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, consumer); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName()); + } + + @Test + public void testOldGetEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR); + verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName()); + + } + + @Test + public void buildConsumerNameWhenAllFieldsAreProvided() { + consumer.setConsumerName(CONSUMER_NAME); + consumer.setConsumerSalt(CONSUMER_SALT); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_NAME + "," + CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenSaltIsNull() { + consumer.setConsumerName(CONSUMER_NAME); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_NAME + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameIsNull() { + consumer.setConsumerName(null); + consumer.setConsumerSalt(CONSUMER_SALT); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameAndPwAreNull() { + consumer.setConsumerName(null); + consumer.setConsumerSalt(CONSUMER_SALT); + assertEquals(CONSUMER_SALT, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenNameAndSaltAreNull() { + consumer.setConsumerName(null); + consumer.setConsumerPassword(CONSUMER_PASSWORD); + assertEquals(CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer)); + } + + @Test + public void buildConsumerNameWhenConsumerObjectIsNull() { + assertEquals("", AuditConsumerEventFactory.buildConsumerName(null)); + } + + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, USER_ID); + + return auditingFields; + } + + private void verifyConsumerEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ConsumerEvent storedEvent = (ConsumerEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getEcompUser()).isEqualTo(USER_ID); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java new file mode 100644 index 0000000000..04bd34f289 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java @@ -0,0 +1,236 @@ +package org.openecomp.sdc.be.auditing.impl; + +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + + +public class AuditTestUtils { + public final static String USER_FIRST_NAME = "Carlos"; + public final static String USER_LAST_NAME = "Santana"; + public final static String USER_ID = "cs0008"; + public final static String DESCRIPTION = "OK"; + public final static String STATUS_OK = "200"; + public final static String STATUS_CREATED = "201"; + public final static String REQUEST_ID = "123456"; + public final static String USER_UID = "Carlos Santana(cs0008)"; + public final static String SERVICE_INSTANCE_ID = "d07fdc15-122d-4476-a349-8c9a2d80b485"; + public final static String CURRENT_STATE = "CERTIFIED"; + public final static String CURRENT_VERSION = "1.1"; + public final static String RESOURCE_TYPE = ResourceTypeEnum.VF.name(); + public final static String RESOURCE_TYPE_VFC = ResourceTypeEnum.VFC.name(); + public final static String RESOURCE_NAME = "ciServicea184822c06e6"; + public final static String DIST_ID = "e5765a82-e7cd-4c5c-91a0-eae58d6ae08f"; + public final static String TOPIC_NAME = "ASDC-DISTR-NOTIF-TOPIC-PROD_TEST"; + public final static String DESIGNER_USER_ROLE = "DESIGNER"; + public final static String TESTER_USER_ROLE = "TESTER"; + public final static String USER_EMAIL = "carlos@email.com"; + public final static String MODIFIER_FIRST_NAME = "Jimmy"; + public final static String MODIFIER_LAST_NAME = "Hendrix"; + public final static String MODIFIER_ID = "jh0003"; + public final static String MODIFIER_UID = "Jimmy Hendrix(jh0003)"; + public final static String USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, DESIGNER"; + public final static String UPDATED_USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, TESTER"; + public final static String VNF_WORKLOAD_CONTEXT = "WORKLOAD"; + public final static String DPREV_STATUS = "DPREV_STATUS"; + public final static String DCURR_STATUS = "DCURR_STATUS"; + + public final static String CONSUMER_NAME = "consumer"; + public final static String CONSUMER_SALT = "2a1f887d607d4515d4066fe0f5452a50"; + public final static String CONSUMER_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"; + + public final static String PREV_RESOURCE_VERSION = "1.0"; + public final static String PREV_RESOURCE_STATE = "READY_FOR_CERTIFICATION"; + public final static String COMMENT = "Attempt to perform"; + public final static String ARTIFACT_DATA = "123456qwertasdfgljkPIPIPIOPI"; + public final static String TOSCA_NODE_TYPE = "tosca.node.Root"; + public final static String ARTIFACT_UUID = "1234-ASDFG_7894443"; + public final static String INVARIANT_UUID = "INV-123456"; + public final static String USER_DETAILS = "All"; + + public final static String STATUS_500 = "500"; + public final static String DESC_ERROR = "Error"; + public final static String MSG_ERROR = "Error: "; + public final static String MSG_OK = "OK: "; + + public final static String DIST_CONSUMER_ID = "ABC-123445678"; + public final static String DIST_RESOURCE_URL = "http://abc.com/res"; + public final static String DIST_STATUS_TOPIC = "STopic"; + public final static String DIST_NOTIFY_TOPIC = "NTopic"; + public final static String DIST_API_KEY = "Key111"; + public final static String DIST_ENV_NAME = "Env111"; + public final static String DIST_ROLE = "Governer"; + public final static String DIST_STATUS_TIME = "154567890123"; + + public final static String AUTH_URL = "http://abc.com/auth"; + public final static String REALM = "12345ABSDF"; + public final static String AUTH_STATUS = "AUTHENTICATED"; + + public final static String CATEGORY = "VFs"; + public final static String SUB_CATEGORY = "Network"; + public final static String GROUPING_NAME = "Group1"; + + public final static String OP_ENV_ID = "12345678"; + public final static String OP_ENV_NAME = "Op1"; + public final static String OP_ENV_TYPE = "ECOMP"; + public final static String OP_ENV_ACTION = "Create"; + public final static String TENANT_CONTEXT = "TENANT"; + + public final static String EXPECTED_USER_ACCESS_LOG_STR = "ACTION = \"" + AuditingActionEnum.USER_ACCESS.getName() + "\" USER = \"" + USER_UID + + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DISTRIB_NOTIFICATION_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_NOTIFY.getName() + + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + + "\" DID = \"" + DIST_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + + "\" TENANT = \"" + TENANT_CONTEXT + "\" VNF_WORKLOAD_CONTEXT = \"" + VNF_WORKLOAD_CONTEXT + "\" ENV_ID = \"" + OP_ENV_ID + "\""; + + public final static String EXPECTED_ADD_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"\" USER_AFTER = \"" + USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_CREATED + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_UPDATE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.UPDATE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"" + UPDATED_USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DELETE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.DELETE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID + + "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CHECK_IN_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHECKIN_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" COMMENT = \"" + COMMENT + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CREATE_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_IMPORT_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.IMPORT_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" TOSCA_NODE_TYPE = \"" + + TOSCA_NODE_TYPE + "\""; + + public final static String EXPECTED_ARTIFACT_UPLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_UPLOAD.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" + + " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" + + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" + + ARTIFACT_UUID + "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_STATE_CHANGE_REQUEST = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + + MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" + + DCURR_STATUS + "\" DID = \"" + DIST_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_STATE_CHANGE_APPROV = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + + MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" + + DCURR_STATUS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" COMMENT = \"" + COMMENT + "\""; + + public final static String EXPECTED_GET_USER_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_USERS_LIST.getName() + "\" MODIFIER = \"" + USER_UID + + "\" DETAILS = \"" + USER_DETAILS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_ACTIVATE_SERVICE_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName() + "\" RESOURCE_TYPE = \"" + + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" MODIFIER = \"" + + MODIFIER_UID + "\" STATUS = \"" + STATUS_OK + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" INVARIANT_UUID = \"" + INVARIANT_UUID + + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR = "CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + + "\" PREV_STATE = \"" + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + + "\" INVARIANT_UUID = \"" + INVARIANT_UUID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" + ARTIFACT_UUID + + "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_ASSET_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ASSET_LIST.getName() + "\" CONSUMER_ID = \"" + + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_TOSCA_MODEL_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_TOSCA_MODEL.getName() + "\" CONSUMER_ID = \"" + + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_AUTH_REQUEST_LOG_STR = "ACTION = \"" + AuditingActionEnum.AUTH_REQUEST.getName() + "\" URL = \"" + + AUTH_URL + "\" USER = \"" + USER_ID + "\" AUTH_STATUS = \"" + AUTH_STATUS + "\" REALM = \"" + REALM + "\""; + + public final static String EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_ADD_CATEGORY_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_CATEGORY.getName() + + "\" MODIFIER = \"" + MODIFIER_UID + "\" CATEGORY_NAME = \"" + CATEGORY + "\" SUB_CATEGORY_NAME = \"" + SUB_CATEGORY + + "\" GROUPING_NAME = \"" + GROUPING_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + private final static String OP_ENV_LOG = "\" OPERATIONAL_ENVIRONMENT_ACTION = \"" + OP_ENV_ACTION + "\" OPERATIONAL_ENVIRONMENT_ID = \"" + OP_ENV_ID + + "\" OPERATIONAL_ENVIRONMENT_NAME = \"" + OP_ENV_NAME + "\" OPERATIONAL_ENVIRONMENT_TYPE = \"" + OP_ENV_TYPE + + "\" TENANT_CONTEXT = \"" + TENANT_CONTEXT + "\""; + + public final static String EXPECTED_CREATE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_ENVIRONMENT.getName() + OP_ENV_LOG; + + public final static String EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName() + OP_ENV_LOG; + + public final static String EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName() + OP_ENV_LOG; + + public final static String EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName() + + "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" ROLE = \"" + DIST_ROLE + "\" API_KEY = \"" + + DIST_API_KEY + "\" STATUS = \"" + STATUS_OK + "\""; + + public final static String EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName() + + "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" STATUS = \"" + STATUS_OK + "\""; + + public final static String EXPECTED_DIST_REG_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_REGISTER.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" API_KEY = \"" + DIST_API_KEY + "\" D_ENV = \"" + DIST_ENV_NAME + "\" STATUS = \"" + + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" DNOTIF_TOPIC = \"" + DIST_NOTIFY_TOPIC + "\" DSTATUS_TOPIC = \"" + DIST_STATUS_TOPIC + "\""; + + public final static String EXPECTED_DIST_STATUS_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATUS.getName() + + "\" DID = \"" + DIST_ID + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME + + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS_TIME = \"" + DIST_STATUS_TIME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DIST_DOWNLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_DISTRIB_DEPLOY_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_DEPLOY.getName() + + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" DID = \"" + DIST_ID + + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\""; + + public final static String EXPECTED_GET_UEB_CLUSTER_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_UEB_CLUSTER.getName() + + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" STATUS = \"" + STATUS_OK + "\" STATUS_DESC = \"" + DESCRIPTION + "\""; + + + public static User user; + public static User modifier; + + public static void init(Configuration.ElasticSearchConfig esConfig) { + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + configurationManager.getConfiguration().setDisableAudit(false); + configurationManager.getConfiguration().setElasticSearch(esConfig); + + user = new User(); + modifier = new User(); + user.setFirstName(USER_FIRST_NAME); + user.setLastName(USER_LAST_NAME); + user.setUserId(USER_ID); + + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java new file mode 100644 index 0000000000..a774dea352 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.auditing.impl.category; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CATEGORY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_CATEGORY_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.GROUPING_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SUB_CATEGORY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditCategoryEventFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddCategoryEvent() { + AuditEventFactory builder = new AuditAddCategoryEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + modifier, CATEGORY, SUB_CATEGORY, GROUPING_NAME, RESOURCE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR); + verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName()); + } + + @Test + public void testOldAddEcompUserCredEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_CATEGORY))).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR); + verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName()); + + } + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, CATEGORY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, SUB_CATEGORY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, GROUPING_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + private void verifyCategoryEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + CategoryEvent storedEvent = (CategoryEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); +// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getCategoryName()).isEqualTo(CATEGORY); + assertThat(storedEvent.getSubCategoryName()).isEqualTo(SUB_CATEGORY); + assertThat(storedEvent.getGroupingName()).isEqualTo(GROUPING_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java new file mode 100644 index 0000000000..199597b82c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java @@ -0,0 +1,191 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_API_KEY; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_NOTIFY_TOPIC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TOPIC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_REG_ENGINE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; + +@RunWith(MockitoJUnitRunner.class) +public class AuditDistrEngineFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewAddKeyEvent() { + AuditEventFactory factory = new AuditAddKeyDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName()); + } + + @Test + public void testOldAddKeyEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL))).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName()); + + } + + @Test + public void testNewCreateTopicEvent() { + AuditEventFactory factory = new AuditCreateTopicDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName()); + } + + @Test + public void testOldCreateTopicEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC))).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName()); + } + + @Test + public void testNewRegisterEvent() { + AuditEventFactory factory = new AuditRegisterDistribEngineEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName()); + } + + @Test + public void testOldRegisterEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_REGISTER))).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR); + verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName()); + } + + private void verifyEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionEngineEvent storedEvent = (DistributionEngineEvent) eventCaptor.getValue(); + assertThat(storedEvent.getDnotifTopic()).isEqualTo(DIST_NOTIFY_TOPIC); + assertThat(storedEvent.getDstatusTopic()).isEqualTo(DIST_STATUS_TOPIC); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getEnvironmentName()).isEqualTo(DIST_ENV_NAME); + assertThat(storedEvent.getApiKey()).isEqualTo(DIST_API_KEY); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getRole()).isEqualTo(DIST_ROLE); + } + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, DIST_ENV_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, DIST_STATUS_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, DIST_NOTIFY_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, DIST_NOTIFY_TOPIC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, DIST_API_KEY); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, DIST_ROLE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java new file mode 100644 index 0000000000..09a168a132 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java @@ -0,0 +1,387 @@ +package org.openecomp.sdc.be.auditing.impl.distribution; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent; +import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TIME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_DEPLOY_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_NOTIFICATION_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_DOWNLOAD_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATUS_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_UEB_CLUSTER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOPIC_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.VNF_WORKLOAD_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user; + +@RunWith(MockitoJUnitRunner.class) +public class AuditDistrEventFuncTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewNotifyEvent() { + AuditEventFactory factory = new AuditDistribNotificationEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + CURRENT_STATE, CURRENT_VERSION, DIST_ID, user, + RESOURCE_NAME, RESOURCE_TYPE, TOPIC_NAME, + new OperationalEnvAuditData(OP_ENV_ID, VNF_WORKLOAD_CONTEXT, TENANT_CONTEXT)); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR); + verifyNotifyEvent(); + } + + @Test + public void testOldNotifyEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillNotifyMap())).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR); + verifyNotifyEvent(); + + } + + @Test + public void testNewStatusEvent() { + AuditEventFactory factory = new AuditDistribStatusEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_ID, DIST_CONSUMER_ID, TOPIC_NAME, DIST_RESOURCE_URL, DIST_STATUS_TIME); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR); + verifyStatusEvent(); + } + + @Test + public void testOldStatusEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillStatusMap())).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR); + verifyStatusEvent(); + } + + @Test + public void testNewDownloadEvent() { + AuditEventFactory factory = new AuditDistribDownloadEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR); + verifyDownloadsEvent(); + } + + @Test + public void testOldDownloadEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillDownloadMap())).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR); + verifyDownloadsEvent(); + } + + @Test + public void testNewDeployEvent() { + AuditEventFactory factory = new AuditDistribDeployEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + CURRENT_VERSION, + DIST_ID, user, RESOURCE_NAME, RESOURCE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR); + verifyDeployEvent(); + } + + @Test + public void testOldDeployEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillDeployMap())).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR); + verifyDeployEvent(); + } + + @Test + public void testNewGetUebClusterEvent() { + AuditEventFactory factory = new AuditGetUebClusterEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + DIST_CONSUMER_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR); + verifyGetUebClusterEvent(); + } + + @Test + public void testOldGetUebClusterEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillGetUebClusterMap())).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR); + verifyGetUebClusterEvent(); + } + + private void verifyNotifyEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionNotificationEvent storedEvent = (DistributionNotificationEvent) eventCaptor.getValue(); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME); + assertThat(storedEvent.getVnfWorkloadContext()).isEqualTo(VNF_WORKLOAD_CONTEXT); + assertThat(storedEvent.getEnvId()).isEqualTo(OP_ENV_ID); + assertThat(storedEvent.getTenant()).isEqualTo(TENANT_CONTEXT); + } + + private void verifyStatusEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionStatusEvent storedEvent = (DistributionStatusEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_STATUS.getName()); + assertThat(storedEvent.getStatusTime()).isEqualTo(DIST_STATUS_TIME); + assertThat(storedEvent.getResoureURL()).isEqualTo(DIST_RESOURCE_URL); + assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME); + } + + private void verifyDownloadsEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionDownloadEvent storedEvent = (DistributionDownloadEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + } + + private void verifyDeployEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + DistributionDeployEvent storedEvent = (DistributionDeployEvent) eventCaptor.getValue(); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + } + + private void verifyGetUebClusterEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + AuditingGetUebClusterEvent storedEvent = (AuditingGetUebClusterEvent) eventCaptor.getValue(); + assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + } + + private EnumMap fillNotifyMap() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, VNF_WORKLOAD_CONTEXT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, TENANT_CONTEXT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, OP_ENV_ID); + + return auditingFields; + } + + private EnumMap fillStatusMap() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_STATUS.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, DIST_STATUS_TIME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + + return auditingFields; + } + + private EnumMap fillDownloadMap() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + private EnumMap fillDeployMap() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME); + + return auditingFields; + } + + private EnumMap fillGetUebClusterMap() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_UEB_CLUSTER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + + return auditingFields; + } + + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java new file mode 100644 index 0000000000..f859b75607 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java @@ -0,0 +1,156 @@ +package org.openecomp.sdc.be.auditing.impl.ecompopenv; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; + +@RunWith(MockitoJUnitRunner.class) +public class AuditEcompOpEnvEventTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewCreateOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.CREATE_ENVIRONMENT, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + } + + @Test + public void testOldCreateOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_ENVIRONMENT))).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + + } + + @Test + public void testNewUnsupportedTypeOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName()); + } + + @Test + public void testOldUnsupportedTypeOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE))).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName()); + } + + @Test + public void testNewUnknownNotificationOpEnvEvent() { + AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION, + OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName()); + } + + @Test + public void testOldUnknownNotificationOpEnvEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION))).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR); + verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName()); + } + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID, OP_ENV_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE, OP_ENV_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME, OP_ENV_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION, OP_ENV_ACTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT, TENANT_CONTEXT); + + return auditingFields; + } + + private void verifyEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + EcompOperationalEnvironmentEvent storedEvent = (EcompOperationalEnvironmentEvent) eventCaptor.getValue(); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(storedEvent.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(storedEvent.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(storedEvent.getTenantContext()).isEqualTo(TENANT_CONTEXT); + + + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java new file mode 100644 index 0000000000..7ddc9a0606 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java @@ -0,0 +1,368 @@ +package org.openecomp.sdc.be.auditing.impl.externalapi; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ACTIVATE_SERVICE_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ASSET_LIST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_TOSCA_MODEL_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditExternalApiEventFuncTest { + + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewActivateServiceEvent() { + AuditEventFactory builder = new AuditActivateServiceExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName()); + } + + @Test + public void testOldActivateServiceEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ACTIVATE_SERVICE_BY_API))).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName()); + + } + + @Test + public void testNewDownloadArtifactEvent() { + AuditEventFactory builder = new AuditDownloadArtifactExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName()); + } + + @Test + public void testOldDownloadArtifactEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DOWNLOAD_ARTIFACT))).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR + " "); + verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName()); + } + + @Test + public void testNewChangeLifecycleEvent() { + AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + } + + @Test + public void testOldChangeLifecycleEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API))).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName()); + + } + + @Test + public void testNewDeleteArtifactEvent() { + AuditEventFactory factory = new AuditDeleteArtByApiCrudExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName()); + } + + @Test + public void testOldDeleteArtifactEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_DELETE_BY_API))).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR + " "); + verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName()); + + } + + @Test + public void testNewGetAssetsListEvent() { + AuditEventFactory factory = new AuditGetAssetListExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName()); + } + + @Test + public void testOldGetAssetsListEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ASSET_LIST))).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName()); + } + + @Test + public void testNewGetToscaModelEvent() { + AuditEventFactory factory = new AuditGetToscaModelExternalApiEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL, + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .build(), + INVARIANT_UUID, modifier, ARTIFACT_DATA); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName()); + } + + @Test + public void testOldGetToscaModelEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_TOSCA_MODEL))).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR); + verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName()); + } + + private void verifyExternalApiEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ExternalApiEvent storedEvent = (ExternalApiEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA); + assertThat(storedEvent.getCurrArtifactUuid()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevArtifactUuid()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getInvariantUuid()).isEqualTo(INVARIANT_UUID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE); + + } + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL); + return auditingFields; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java new file mode 100644 index 0000000000..18bd41c765 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java @@ -0,0 +1,432 @@ +package org.openecomp.sdc.be.auditing.impl.resourceadmin; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ARTIFACT_UPLOAD_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHECK_IN_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_APPROV; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_REQUEST; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_IMPORT_RESOURCE_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE_VFC; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; + +@RunWith(MockitoJUnitRunner.class) +public class AuditResourceAdminEventFuncTest { + private AuditingManager auditingManager; + + @Mock + private static AuditCassandraDao cassandraDao; + @Mock + private static ConfigurationSource configurationSource; + @Mock + private static AuditingDao auditingDao; + @Mock + private static Configuration.ElasticSearchConfig esConfig; + + @Captor + private ArgumentCaptor eventCaptor; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + ThreadLocalsHolder.setUuid(REQUEST_ID); + } + + @Test + public void testNewCheckInResourceAdminEvent() { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + AuditEventFactory factory = new AuditCertificationResourceAdminEventFactory( + AuditingActionEnum.CHECKIN_RESOURCE, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName()); + } + + @Test + public void testOldCheckInResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHECKIN_RESOURCE))).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName()); + + } + + private EnumMap fillMap(AuditingActionEnum action) { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE_VFC); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, COMMENT); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, DCURR_STATUS); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, DPREV_STATUS); + + if (action == AuditingActionEnum.IMPORT_RESOURCE) { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, TOSCA_NODE_TYPE); + } + else { + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, Constants.EMPTY_STRING); + } + + return auditingFields; + } + + @Test + public void testNewCreateResourceAdminEvent() { + + AuditEventFactory factory = new AuditCreateUpdateResourceAdminEventFactory( + AuditingActionEnum.CREATE_RESOURCE, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID, Constants.EMPTY_STRING); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName()); + } + + @Test + public void testOldCreateResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_RESOURCE))).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName()); + + } + + @Test + public void testNewImportResourceAdminEvent() { + + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.setVersion(CURRENT_VERSION); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setState(LifecycleStateEnum.CERTIFIED); + resource.setToscaType(TOSCA_NODE_TYPE); + + AuditEventFactory factory = new AuditImportResourceAdminEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID, TOSCA_NODE_TYPE); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName()); + } + + @Test + public void testOldImportResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.IMPORT_RESOURCE))).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName()); + + } + + @Test + public void testNewArtifactUploadResourceAdminEvent() { + + AuditEventFactory factory = new AuditArtifactResourceAdminEventFactory( + AuditingActionEnum.ARTIFACT_UPLOAD, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_UPLOAD.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName()); + } + + @Test + public void testOldArtifactUploadResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_UPLOAD))).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR + " "); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName()); + + } + + @Test + public void testNewDistStateChangeRequestResourceAdminEvent() { + + AuditEventFactory factory = new AuditDistStateChangeRequestResourceAdminEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + } + + @Test + public void testOldDistStateChangeRequestResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); + } + + @Test + public void testNewDistStateChangeApprovResourceAdminEvent() { + + AuditEventFactory factory = new AuditDistStateChangeResourceAdminEventFactory( + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .serviceInstanceId(SERVICE_INSTANCE_ID) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .distributionStatus(DPREV_STATUS) + .build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .distributionStatus(DCURR_STATUS) + .build(), + RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier, + ARTIFACT_DATA, COMMENT, DIST_ID); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName()); + } + + @Test + public void testOldDistStateChangeApprovResourceAdminEvent() { + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName()); + } + + + private void verifyResourceAdminEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + ResourceAdminEvent storedEvent = (ResourceAdminEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(storedEvent.getAction()).isEqualTo(action); + assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA); + assertThat(storedEvent.getComment()).isEqualTo(COMMENT); + assertThat(storedEvent.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(storedEvent.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(storedEvent.getDprevStatus()).isEqualTo(DPREV_STATUS); + assertThat(storedEvent.getDid()).isEqualTo(DIST_ID); + assertThat(storedEvent.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME); + assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE_VFC); + + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(storedEvent.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } else { + assertThat(storedEvent.getToscaNodeType()).isEmpty(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java new file mode 100644 index 0000000000..4a5b1bbd59 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java @@ -0,0 +1,395 @@ +package org.openecomp.sdc.be.auditing.impl.usersadmin; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.impl.AuditingDao; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; +import org.openecomp.sdc.be.resources.data.auditing.AuthEvent; +import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; + +import java.util.EnumMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_AUTH_REQUEST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_USER_LIST_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UPDATE_USER_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_USER_ACCESS_LOG_STR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REALM; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_CREATED; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_DETAILS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user; + +@RunWith(MockitoJUnitRunner.class) +public class AuditUserEventFuncTest { + @Mock + private static AuditCassandraDao cassandraDao; + @Captor + private ArgumentCaptor eventCaptor; + @Mock + private static AuditingDao auditingDao; + @Mock + private Configuration.ElasticSearchConfig esConfig; + + private AuditingManager auditingManager; + + @Before + public void setUp() { + init(esConfig); + auditingManager = new AuditingManager(auditingDao, cassandraDao); + } + + @Test + public void testNewUserAccessEvent() { + AuditEventFactory factory = new AuditUserAccessEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + user); + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR); + verifyUserAccessEvent(); + } + + @Test + public void testOldUserAccessEvent() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.USER_ACCESS.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')'); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR); + verifyUserAccessEvent(); + } + + @Test + public void testNewUserAdminEventForAddUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.ADD_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_CREATED) + .requestId(REQUEST_ID) + .build(), + modifier, null, user); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.ADD_USER.getName()); + } + + @Test + public void testOldUserAdminEventForAddUser() { + user.setRole(TESTER_USER_ROLE); + user.setEmail(USER_EMAIL); + + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.ADD_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_CREATED); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, USER_EXTENDED_NAME); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_ADD_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.ADD_USER.getName()); + } + + @Test + public void testNewUserAdminEventForUpdateUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + User updated = new User(user); + updated.setRole(TESTER_USER_ROLE); + + AuditEventFactory builder = new AuditUserAdminEventFactory(AuditingActionEnum.UPDATE_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + modifier, user, updated); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName()); + } + + @Test + public void testOldUserAdminEventForUpdateUser() { + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + User updated = new User(user); + updated.setRole(TESTER_USER_ROLE); + + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.UPDATE_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, UPDATED_USER_EXTENDED_NAME); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName()); + } + + @Test + public void testNewUserAdminEventForDeleteUser() { + + user.setRole(DESIGNER_USER_ROLE); + user.setEmail(USER_EMAIL); + + AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.DELETE_USER, + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + modifier, user, null); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.DELETE_USER.getName()); + } + + @Test + public void testOldUserAdminEventForDeleteUser() { + user.setRole(TESTER_USER_ROLE); + user.setEmail(USER_EMAIL); + + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DELETE_USER.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, null); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR); + verifyUserEvent(AuditingActionEnum.DELETE_USER.getName()); + } + + @Test + public void testNewGetUserListEvent() { + + AuditEventFactory factory = new AuditGetUsersListEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + user, USER_DETAILS); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR); + verifyGetUserListEvent(); + } + + @Test + public void testOldGetUserListEvent() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_USERS_LIST.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, USER_DETAILS); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR); + verifyGetUserListEvent(); + } + + @Test + public void testNewAuthRequestEvent() { + + AuditEventFactory factory = new AuditAuthRequestEventFactory( + CommonAuditData.newBuilder() + .description(DESCRIPTION) + .status(STATUS_OK) + .requestId(REQUEST_ID) + .build(), + USER_ID, AUTH_URL, REALM, AUTH_STATUS); + + when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR); + verifyAuthRequestEvent(); + } + + @Test + public void testOldAuthRequestEvent() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.AUTH_REQUEST.getName()); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, USER_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, REALM); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, AUTH_URL); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, AUTH_STATUS); + + when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType()))) + .thenReturn(ActionStatus.OK); + when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK); + + assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR); + verifyAuthRequestEvent(); + } + + + private void verifyUserEvent(String action) { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + UserAdminEvent storedEvent = (UserAdminEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); +// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); - it is not filled out by the old code!!! + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(action); + if (action.equals(AuditingActionEnum.ADD_USER.getName())) { + //TODO enable this test after deleting the old auditEvent method +// assertThat(storedEvent.getUserBefore()).isNull(); + assertThat(storedEvent.getUserAfter()).isEqualTo(USER_EXTENDED_NAME); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_CREATED); + } + else if (action.equals(AuditingActionEnum.UPDATE_USER.getName())){ + assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME); + assertThat(storedEvent.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + } + else { + assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME); + //TODO enable this test after deleting the old auditEvent method +// assertThat(storedEvent.getUserAfter()).isNull(); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + } + } + + private void verifyGetUserListEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + GetUsersListEvent storedEvent = (GetUsersListEvent) eventCaptor.getValue(); + assertThat(storedEvent.getModifier()).isEqualTo(USER_UID); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.GET_USERS_LIST.getName()); + } + + private void verifyUserAccessEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + UserAccessEvent storedEvent = (UserAccessEvent) eventCaptor.getValue(); + assertThat(storedEvent.getUserUid()).isEqualTo(USER_UID); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isNotBlank(); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.USER_ACCESS.getName()); + } + + private void verifyAuthRequestEvent() { + verify(cassandraDao).saveRecord(eventCaptor.capture()); + AuthEvent storedEvent = (AuthEvent) eventCaptor.getValue(); + assertThat(storedEvent.getUser()).isEqualTo(USER_ID); + assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK); + assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION); + assertThat(storedEvent.getRequestId()).isNotBlank(); + assertThat(storedEvent.getServiceInstanceId()).isNull(); + assertThat(storedEvent.getAuthStatus()).isEqualTo(AUTH_STATUS); + assertThat(storedEvent.getUrl()).isEqualTo(AUTH_URL); + assertThat(storedEvent.getRealm()).isEqualTo(REALM); + assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.AUTH_REQUEST.getName()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java index 87dfbc45de..06c22bca69 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,56 +20,53 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import java.util.EnumMap; -import java.util.UUID; - import org.junit.Before; import org.junit.Test; -import org.mockito.InjectMocks; +import org.junit.runner.RunWith; +import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.impl.AuditingDao; -import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import junit.framework.Assert; +import java.util.EnumMap; +import java.util.UUID; -public class AuditingManagerTest extends BaseConfDependentTest{ +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; - @InjectMocks - private AuditingManager auditingManager = Mockito.spy(AuditingManager.class); - public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class); +@RunWith(MockitoJUnitRunner.class) +public class AuditingManagerTest extends BeConfDependentTest { - public AuditingManagerTest() { - } + private AuditingManager auditingManager; + @Mock + private AuditingDao auditingDao; - @SuppressWarnings("unchecked") - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); + @Before + public void setup() { + auditingManager = new AuditingManager(auditingDao, null); + when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK); - } + } - @Test - public void testNormalizeEmptyStringValuesAndUuid() { - EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); - auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); + @Test + public void testNormalizeEmptyStringValuesAndUuid() { + EnumMap auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create"); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null); + auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null "); - String randomUUID = UUID.randomUUID().toString(); - ThreadLocalsHolder.setUuid(randomUUID); + String randomUUID = UUID.randomUUID().toString(); + ThreadLocalsHolder.setUuid(randomUUID); - auditingManager.auditEvent(auditingFields); - // Checking normalization - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC), Constants.EMPTY_STRING); - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT), Constants.EMPTY_STRING); - Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID), randomUUID); - } + auditingManager.auditEvent(auditingFields); + // Checking normalization + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT).toString()).isEmpty(); + assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)).isEqualTo(randomUUID); + } } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java deleted file mode 100644 index ad5471e852..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.components; - -import java.io.File; - -import org.junit.BeforeClass; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; - -public class BaseConfDependentTest { - protected static ConfigurationManager configurationManager; - - @BeforeClass - public static void setupBeforeClass() { - - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - configurationManager = new ConfigurationManager(configurationSource); - - configurationManager.getConfiguration().setTitanInMemoryGraph(true); - - } -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java new file mode 100644 index 0000000000..bbd827eb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java @@ -0,0 +1,355 @@ +package org.openecomp.sdc.be.components; + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.mockito.Mockito; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +public class BaseServiceBusinessLogicTest { + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + ForwardingPathOperation forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = null; + + protected static final String CERTIFIED_VERSION = "1.0"; + protected static final String UNCERTIFIED_VERSION = "0.2"; + protected static final String COMPONNET_ID = "myUniqueId"; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static Map FILTER_MAP_CERTIFIED_VERSION = new HashMap<>(); + protected static Map FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<>(); + protected static Map FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<>(); + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + //forwardingPath + when(forwardingPathOperation.addForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.updateForwardingPath(any(),any())).thenReturn(Either.left(createMockPath())); + when(forwardingPathOperation.deleteForwardingPath(any(),any())).thenReturn(Either.left(Sets.newHashSet("Wow-It-Works"))); + when(toscaOperationFacade.getToscaElement("delete_forward_test")).thenReturn(Either.left(createServiceObject(true))); + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setForwardingPathOperation(forwardingPathOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + protected Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j, + // ActionStatus> >() { + // public Either, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either, ActionStatus> either; + // final List list; + // Object[] args = invocation.getArguments(); + // Map filterMap = + // (Map) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List list = new ArrayList() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List listPrev = new ArrayList(); + Either, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List listCurr = new ArrayList() { + { + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + protected Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List tgs = new ArrayList(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + return service; + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected static ForwardingPathDataDefinition forwardingPathDataDefinition; + + protected static ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null){ + return forwardingPathDataDefinition ; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol("http"); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode","toNode", "333","444","2222","5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode","toNode2", "4444","44444","4","44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java new file mode 100644 index 0000000000..01d003f2a4 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components; + +import org.junit.BeforeClass; +import org.openecomp.sdc.common.test.BaseConfDependent; + +public class BeConfDependentTest extends BaseConfDependent { + @BeforeClass + public static void setupBeforeClass() { + componentName = "catalog-be"; + confPath = "src/test/resources/config"; + setUp(); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java index 7774b7f412..d7bfdcd1a4 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,80 +42,85 @@ import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ComponentBusinessLogicTest { - private static final User USER = new User(); - private static final String ARTIFACT_LABEL = "toscaArtifact1"; - private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; - - @InjectMocks - private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { - @Override - public Either, ResponseFormat> deleteMarkedComponents() { - return null; - } - - @Override - public ComponentInstanceBusinessLogic getComponentInstanceBL() { - return null; - } - - @Override - public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { - return null; - } - - @Override - public Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn) { - return null; - } - }; - - @Mock - private ArtifactsBusinessLogic artifactsBusinessLogic; - - @BeforeClass - public static void setUp() throws Exception { - new DummyConfigurationManager(); - } - - @SuppressWarnings("unchecked") - @Test - public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { - Resource resource = new ResourceBuilder().setUniqueId("uid") - .setComponentType(ComponentTypeEnum.RESOURCE) - .setSystemName("myResource") - .build(); - Map artifactsFromConfig = new HashMap<>(); - artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); - artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); - when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); - when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) - .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); - testInstance.setToscaArtifactsPlaceHolders(resource, USER); - - Map toscaArtifacts = resource.getToscaArtifacts(); - assertThat(toscaArtifacts).hasSize(2); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); - assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); - ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); - assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); - } - - private Map buildArtifactMap(String artifactName) { - Map artifact = new HashMap<>(); - artifact.put("artifactName", artifactName); - return artifact; - } - - private ArtifactDefinition buildArtifactDef(String artifactLabel) { - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - artifactDefinition.setArtifactLabel(artifactLabel); - return artifactDefinition; - } + private static final User USER = new User(); + private static final String ARTIFACT_LABEL = "toscaArtifact1"; + private static final String ARTIFACT_LABEL2 = "toscaArtifact2"; + + @InjectMocks + private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() { + @Override + public Either, ResponseFormat> deleteMarkedComponents() { + return null; + } + + @Override + public ComponentInstanceBusinessLogic getComponentInstanceBL() { + return null; + } + + @Override + public Either, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) { + return null; + } + + @Override + public Either getUiComponentDataTransferByComponentId(String componentId, List dataParamsToReturn) { + return null; + } + }; + + @Mock + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @BeforeClass + public static void setUp() throws Exception { + new DummyConfigurationManager(); + } + + @SuppressWarnings("unchecked") + @Test + public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception { + Resource resource = new ResourceBuilder().setUniqueId("uid") + .setComponentType(ComponentTypeEnum.RESOURCE) + .setSystemName("myResource") + .build(); + Map artifactsFromConfig = new HashMap<>(); + artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml")); + artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar")); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL)); + when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA)) + .thenReturn(buildArtifactDef(ARTIFACT_LABEL2)); + testInstance.setToscaArtifactsPlaceHolders(resource, USER); + + Map toscaArtifacts = resource.getToscaArtifacts(); + assertThat(toscaArtifacts).hasSize(2); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL); + assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml"); + ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2); + assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar"); + } + + private Map buildArtifactMap(String artifactName) { + Map artifact = new HashMap<>(); + artifact.put("artifactName", artifactName); + return artifact; + } + + private ArtifactDefinition buildArtifactDef(String artifactLabel) { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactLabel(artifactLabel); + return artifactDefinition; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java index 9bf7f16a50..c114f340b8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java @@ -20,10 +20,6 @@ package org.openecomp.sdc.be.components; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,206 +42,193 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import javax.servlet.ServletContext; + +import static org.mockito.Mockito.when; /** * tests GroupBusinessLogic class * @author ns019t * */ public class GroupBusinessLogicTest { - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); - ComponentsUtils componentsUtils = new ComponentsUtils(); - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - final ServletContext servletContext = Mockito.mock(ServletContext.class); - private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); - private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); - private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); - private static User user = Mockito.mock(User.class); - private static String componentId = "vfUniqueId-xxxx"; - private static String groupUniqueId = "groupUniqueId-xxxx"; - @InjectMocks - static GroupBusinessLogic bl = new GroupBusinessLogic(); - - - @Before - public void setupBeforeMethod() { - MockitoAnnotations.initMocks(this); - ExternalConfiguration.setAppName("catalog-be"); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - } - @BeforeClass - public static void setupBeforeClass() { - when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); -// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); - } - - public enum ResponseEnum{ - INVALID_MIN_MAX("SVC4654"), - INVALID_INITIAL_COUNT("SVC4655"); - - String messageId; - - private ResponseEnum(String messageId){ - this.messageId = messageId; - } - public String getMessageId() { - return messageId; - } - - } - /** - * tests the ValidateMinMaxAndInitialCountPropertyValues() method - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testValidateMinMaxAndInitialCountPropertyValues(){ - -// Class targetClass = GroupBusinessLogic.class; -// String methodName = "validateMinMaxAndInitialCountPropertyValues"; -// Either validationRes; -// -// Map parentPropertyValues = new EnumMap<>(PropertyNames.class); -// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map parentPropertyValues1 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); -// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map parentPropertyValues2 = new EnumMap<>(PropertyNames.class); -// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); -// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); -// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); -// -// Map validNewPropertyValues = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); -// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); -// -// Map validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); -// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); -// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); -// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); -// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); -// -// Map invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); -// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); -// -// Map invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); -// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); -// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); -// -// Map invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); -// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); -// -// Map invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); -// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); -// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); -// -// Map invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); -// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); -// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); -// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); -// -// -// Class[] argClasses = {Map.class, Map.class}; -// try { -// Method method = targetClass.getDeclaredMethod(methodName, argClasses); -// method.setAccessible(true); -// -// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects2); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects3); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects7); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); -// -// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects1); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; -// validationRes = (Either) method.invoke(bl, argObjects5); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; -// validationRes = (Either) method.invoke(bl, argObjects6); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; -// validationRes = (Either) method.invoke(bl, argObjects9); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isLeft()); -// assertTrue(validationRes.left().value()); -// -// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects4); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// -// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; -// validationRes = (Either) method.invoke(bl, argObjects8); -// assertTrue(validationRes != null); -// assertTrue(validationRes.isRight()); -// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); -// } -// catch (Exception e) { -// e.printStackTrace(); -// } - } + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + ComponentsUtils componentsUtils; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class); + private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class); + private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class); + private static User user = Mockito.mock(User.class); + private static String componentId = "vfUniqueId-xxxx"; + private static String groupUniqueId = "groupUniqueId-xxxx"; + @InjectMocks + static GroupBusinessLogic bl = new GroupBusinessLogic(); + + + @Before + public void setupBeforeMethod() { + MockitoAnnotations.initMocks(this); + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + + bl.setComponentsUtils(componentsUtils); + } + @BeforeClass + public static void setupBeforeClass() { + when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK); +// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition)); + } + + /** + * tests the ValidateMinMaxAndInitialCountPropertyValues() method + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void testValidateMinMaxAndInitialCountPropertyValues(){ + +// Class targetClass = GroupBusinessLogic.class; +// String methodName = "validateMinMaxAndInitialCountPropertyValues"; +// Either validationRes; +// +// Map parentPropertyValues = new EnumMap<>(PropertyNames.class); +// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map parentPropertyValues1 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null); +// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map parentPropertyValues2 = new EnumMap<>(PropertyNames.class); +// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20"); +// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null"); +// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40"); +// +// Map validNewPropertyValues = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100"); +// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50"); +// +// Map validNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90"); +// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map validNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map validNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40"); +// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null"); +// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map validNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null); +// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60"); +// +// Map invalidNewPropertyValues = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20"); +// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5"); +// +// Map invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5"); +// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10"); +// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20"); +// +// Map invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25"); +// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100"); +// +// Map invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null); +// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95"); +// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10"); +// +// Map invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class); +// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30"); +// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80"); +// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null); +// +// +// Class[] argClasses = {Map.class, Map.class}; +// try { +// Method method = targetClass.getDeclaredMethod(methodName, argClasses); +// method.setAccessible(true); +// +// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects2); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects3); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects7); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId())); +// +// Object[] argObjects = {validNewPropertyValues, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects1); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2}; +// validationRes = (Either) method.invoke(bl, argObjects5); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1}; +// validationRes = (Either) method.invoke(bl, argObjects6); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1}; +// validationRes = (Either) method.invoke(bl, argObjects9); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isLeft()); +// assertTrue(validationRes.left().value()); +// +// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects4); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// +// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues}; +// validationRes = (Either) method.invoke(bl, argObjects8); +// assertTrue(validationRes != null); +// assertTrue(validationRes.isRight()); +// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId())); +// } +// catch (Exception e) { +// e.printStackTrace(); +// } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java index 2a34baeb0f..04c2100ed8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java @@ -20,66 +20,66 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - import org.junit.Test; -import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.api.HealthCheckInfo; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HealthCheckBusinessLogicTest { - HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); - - @Test - public void checkStausUpdated() { + HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic(); + + @Test + public void checkStausUpdated() { - boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); - assertFalse("check false", statusChanged); + boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null); + assertFalse("check false", statusChanged); - List checkInfosLeft = new ArrayList(); - List checkInfosRight = new ArrayList(); + List checkInfosLeft = new ArrayList(); + List checkInfosRight = new ArrayList(); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); - HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); + HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null); + HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null); - /* - * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); - */ + /* + * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null); + */ - checkInfosLeft.add(checkInfoTitanUp); + checkInfosLeft.add(checkInfoTitanUp); - checkInfosRight.add(checkInfoTitanUp); + checkInfosRight.add(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - checkInfosRight.remove(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.remove(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanDown); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.add(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.remove(checkInfoTitanDown); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertTrue("check true", statusChanged); + checkInfosRight.remove(checkInfoTitanDown); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertTrue("check true", statusChanged); - checkInfosRight.add(checkInfoTitanUp); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); - assertFalse("check false", statusChanged); + checkInfosRight.add(checkInfoTitanUp); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight); + assertFalse("check false", statusChanged); - statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); - assertTrue("check true", statusChanged); + statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null); + assertTrue("check true", statusChanged); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java new file mode 100644 index 0000000000..f9412c1643 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java @@ -0,0 +1,143 @@ +package org.openecomp.sdc.be.components; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datamodel.ServiceRelations; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class PathTest extends BaseServiceBusinessLogicTest { + public static final String fromNode = "fromNode"; + + @Override + protected Service createServiceObject(boolean afterCreate) { + Service service = super.createServiceObject(afterCreate); + ArrayList resourceInstancesRelations = new ArrayList<>(); + String toNode = "toNode"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode, "1", toNode, "2", "capability", "3", "requirement", "4")); + String fromNode1 = "fromNode1"; + String toNode1 = "toNode1"; + resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode1, "11", toNode1, "21", "capability1", "31", "requirement1", "41")); + service.setComponentInstances(new java.util.ArrayList<>()); + service.getComponentInstances().add(getComponentInstance(fromNode, "fromNode")); + service.getComponentInstances().add(getComponentInstance(fromNode1, "fromNode1")); + service.getComponentInstances().add(getComponentInstance(toNode, toNode)); + service.getComponentInstances().add(getComponentInstance(toNode1, toNode1)); + + service.setComponentInstancesRelations(resourceInstancesRelations); + return service; + } + + private ComponentInstance getComponentInstance(String uniquId, String normalizedName) { + ComponentInstance ci = new ComponentInstance(); + ci.setUniqueId(uniquId); + ci.setNormalizedName(normalizedName); + ci.setName(normalizedName); + HashMap> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + capabilityDefinition = getCapabilityDefinition(ci); + capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition)); + ci.setCapabilities(capabilities); + return ci; + } + + private static int i = 0; + + private CapabilityDefinition getCapabilityDefinition(ComponentInstance ci) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setUniqueId(UUID.randomUUID().toString()); + capabilityDefinition.setName("My name " + i++); + capabilityDefinition.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + capabilityDefinition.setOwnerId(ci.getUniqueId()); + return capabilityDefinition; + } + + + protected RequirementCapabilityRelDef createRequirementCapabilityRelDef(String fromNode, String fromNodeId, String toNode, String toNodeId, String capability, String capabilityId, String requirement, String requirementId) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(fromNode); + requirementCapabilityRelDef.setRelationships(new ArrayList<>()); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType("something.LINK"); + requirementCapabilityRelDef.getRelationships().add(capabilityRequirementRelationship); + requirementCapabilityRelDef.setToNode(toNode); + return requirementCapabilityRelDef; + } + + @Test + public void validateSerialization() throws IOException { + Service service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("Name"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + ObjectMapper mapper = new ObjectMapper(); + String jsonResult = mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(service); + System.out.println(jsonResult); + + Either serviceResponseFormatEither = new ComponentsUtils(Mockito.mock(AuditingManager.class)).convertJsonToObjectUsingObjectMapper(jsonResult, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); + assertTrue(serviceResponseFormatEither.isLeft()); + Map paths = serviceResponseFormatEither.left().value().getForwardingPaths(); + assertEquals(paths.size(), 1); + ForwardingPathDataDefinition forwardingPathDataDefinition = paths.values().stream().findAny().get(); + assertEquals(protocol, forwardingPathDataDefinition.getProtocol()); + List listToscaDataDefinition = forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition(); + assertEquals(3, listToscaDataDefinition.size()); + assertTrue(listToscaDataDefinition.get(0).getFromNode().equals(nodeA)); + } + + @Test + public void shouldReturnEmptyRelationsObjectsWhenNoComponentInstanceExist() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(super.createServiceObject(false)); + assertTrue(serviceRelations.isEmpty()); + } + + @Test + public void convertServiceToServiceRelations() { + ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(createServiceObject(false)); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String resultString = gson.toJson(serviceRelations); + System.out.println(" RESPONSE BODY: " + resultString); + assertTrue(resultString.contains(fromNode)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java index 572804636d..38aaf92335 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -20,17 +20,8 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; +import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -38,6 +29,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -60,171 +52,152 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; -import fj.data.Either; -import junit.framework.Assert; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class PropertyBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName()); - @Mock - private ServletContext servletContext; - @Mock - private IPropertyOperation propertyOperation; - @Mock - private WebAppContextWrapper webAppContextWrapper; - @Mock - private UserBusinessLogic mockUserAdmin; - @Mock - private WebApplicationContext webAppContext; - @Mock - private ComponentsUtils componentsUtils; - @Mock - private ToscaOperationFacade toscaOperationFacade; - - @InjectMocks - private PropertyBusinessLogic bl = new PropertyBusinessLogic(); - private User user = null; - private String resourceId = "resourceforproperty.0.1"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // User data and management - user = new User(); - user.setUserId("jh003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); -// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - - // Resource Operation mock methods - // getCount -// Either eitherCount = Either.left(0); -// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); -// Either eitherCountExist = Either.left(1); -// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); -// Either eitherCountRoot = Either.left(1); -// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); + private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class); + @Mock + private ServletContext servletContext; + @Mock + private IPropertyOperation propertyOperation; + @Mock + private WebAppContextWrapper webAppContextWrapper; + @Mock + private UserBusinessLogic mockUserAdmin; + @Mock + private WebApplicationContext webAppContext; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private UserValidations userValidations; + + @InjectMocks + private PropertyBusinessLogic bl = new PropertyBusinessLogic(); + private User user = null; + private String resourceId = "resourceforproperty.0.1"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq("jh003"), anyString(), eq(false))).thenReturn(Either.left(user)); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); +// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + + // Resource Operation mock methods + // getCount +// Either eitherCount = Either.left(0); +// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount); +// Either eitherCountExist = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist); +// Either eitherCountRoot = Either.left(1); +// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot); // -// Either eitherGetResource = Either.left(createResourceObject(true)); -// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName("MyResourceName"); - resource.addCategory("Generic", "VoIP"); - resource.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test"); - resource.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - - if (afterCreate) { - resource.setName(resource.getName().toLowerCase()); - resource.setVersion("0.1"); - ; - resource.setUniqueId(resourceId); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - } - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - log.debug(gson.toJson(resource)); - return resource; - } - - // @Test - public void testHappyScenario() { - - String propertyName = "disk_size"; - PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); - Either, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); - - if (either.isRight()) { - Assert.assertFalse(true); - } - Assert.assertEquals(newPropertyDefinition, either.left().value()); - } - - @Test - public void getProperty_propertyNotFound() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); - resource.setProperties(Arrays.asList(property1, property2)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); - assertTrue(nonExistingProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty_propertyNotBelongsToResource() throws Exception { - Resource resource = new Resource(); - PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); - resource.setProperties(Arrays.asList(property1)); - String resourceId = "myResource"; - resource.setUniqueId(resourceId); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); - assertTrue(notFoundProperty.isRight()); - Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); - } - - @Test - public void getProperty() throws Exception { - Resource resource = new Resource(); - resource.setUniqueId(resourceId); - PropertyDefinition property1 = createPropertyObject("someProperty", null); - resource.setProperties(Arrays.asList(property1)); - - Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); - assertTrue(foundProperty.isLeft()); - assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); - } - - private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { - PropertyDefinition pd = new PropertyDefinition(); - List constraints = new ArrayList(); - pd.setConstraints(null); - pd.setDefaultValue("100"); - pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); - pd.setPassword(false); - pd.setRequired(true); - pd.setType("Integer"); - pd.setOwnerId(resourceId); - pd.setUniqueId(resourceId + "." + propertyName); - return pd; - } +// Either eitherGetResource = Either.left(createResourceObject(true)); +// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource); + + } + + // @Test + public void testHappyScenario() { + + String propertyName = "disk_size"; + PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId); + Either, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId()); + + if (either.isRight()) { + Assert.assertFalse(true); + } + Assert.assertEquals(newPropertyDefinition, either.left().value()); + } + + @Test + public void getProperty_propertyNotFound() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource"); + resource.setProperties(Arrays.asList(property1, property2)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); + assertTrue(nonExistingProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty_propertyNotBelongsToResource() throws Exception { + Resource resource = new Resource(); + PropertyDefinition property1 = createPropertyObject("someProperty", "someResource"); + resource.setProperties(Arrays.asList(property1)); + String resourceId = "myResource"; + resource.setUniqueId(resourceId); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); + assertTrue(notFoundProperty.isRight()); + Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); + } + + @Test + public void getProperty() throws Exception { + Resource resource = new Resource(); + resource.setUniqueId(resourceId); + PropertyDefinition property1 = createPropertyObject("someProperty", null); + resource.setProperties(Arrays.asList(property1)); + + Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + Either, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); + assertTrue(foundProperty.isLeft()); + assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); + } + + private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { + PropertyDefinition pd = new PropertyDefinition(); + List constraints = new ArrayList(); + pd.setConstraints(null); + pd.setDefaultValue("100"); + pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node"); + pd.setPassword(false); + pd.setRequired(true); + pd.setType("Integer"); + pd.setOwnerId(resourceId); + pd.setUniqueId(resourceId + "." + propertyName); + return pd; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java index 30e12e85d0..82389822f3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.BeforeClass; @@ -37,7 +28,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ImportUtils; import org.openecomp.sdc.be.components.impl.ImportUtilsTest; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; @@ -63,310 +54,313 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.PolicyException; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class ResourceImportManagerTest { - private static ConfigurationManager configurationManager; - static ResourceImportManager importManager; - static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class); - static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); - static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); - static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); - static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - static Logger log = Mockito.spy(Logger.class); - - @BeforeClass - public static void beforeClass() throws IOException { - importManager = new ResourceImportManager(); - importManager.setAuditingManager(auditingManager); - when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); - importManager.setResponseFormatManager(responseFormatManager); - importManager.setResourceBusinessLogic(resourceBusinessLogic); - importManager.setToscaOperationFacade(toscaOperationFacade); - ResourceImportManager.setLog(log); - - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - - Configuration configuration = new Configuration(); - configuration.setTitanInMemoryGraph(true); - configurationManager.setConfiguration(configuration); - } + private static ConfigurationManager configurationManager; + static ResourceImportManager importManager; + static AuditingManager auditingManager = Mockito.mock(AuditingManager.class); + static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class); + static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + @BeforeClass + public static void beforeClass() throws IOException { + importManager = new ResourceImportManager(); + importManager.setAuditingManager(auditingManager); + when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null)); + importManager.setResponseFormatManager(responseFormatManager); + importManager.setResourceBusinessLogic(resourceBusinessLogic); + importManager.setToscaOperationFacade(toscaOperationFacade); + + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + Configuration configuration = new Configuration(); + configuration.setTitanInMemoryGraph(true); + configurationManager.setConfiguration(configuration); + } + + @Before + public void beforeTest() { + Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin); + } + + @Test + public void testBasicResourceCreation() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); - @Before - public void beforeTest() { - Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log); - } + User user = new User(); + user.setUserId(resourceMD.getContactId()); + user.setRole("ADMIN"); + user.setFirstName("Jhon"); + user.setLastName("Doh"); + Either eitherUser = Either.left(user); - @Test - public void testBasicResourceCreation() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - user.setRole("ADMIN"); - user.setFirstName("Jhon"); - user.setLastName("Doh"); - Either eitherUser = Either.left(user); + setResourceBusinessLogicMock(); - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml"); - - Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - Resource resource = createResource.left().value().left; - - testSetConstantMetaData(resource); - testSetMetaDataFromJson(resource, resourceMD); - - testSetDerivedFrom(resource); - testSetProperties(resource); - - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - } - - @Test - public void testResourceCreationFailed() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either eitherUser = Either.left(user); - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); - - when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); - setResourceBusinessLogicMock(); - - String jsonContent = "this is an invalid yml!"; - - Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isRight()); - ResponseFormat errorInfoFromTest = createResource.right().value(); - assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); - assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); - assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); - Mockito.verify(log).debug(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Exception.class)); - // Mockito.verify(log).error(Mockito.anyString(), Mockito.anyString(), - // Mockito.anyString()); - - Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)); - - Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - - } - - @Test - public void testResourceCreationWithCapabilities() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either eitherUser = Either.left(user); - - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); - - Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - Resource resource = createResource.left().value().left; - testSetCapabilities(resource); - - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); - Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); - - } - - @Test - public void testResourceCreationWithRequirments() throws IOException { - UploadResourceInfo resourceMD = createDummyResourceMD(); - User user = new User(); - user.setUserId(resourceMD.getContactId()); - Either eitherUser = Either.left(user); - - when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); - - setResourceBusinessLogicMock(); - - String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); - - Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); - assertTrue(createResource.isLeft()); - testSetRequirments(createResource.left().value().left); - - } - - private void setResourceBusinessLogicMock() { - when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); - when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) - .thenAnswer(new Answer, ResponseFormat>>() { - public Either, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left(new ImmutablePair((Resource) args[0], ActionStatus.CREATED)); - - } - }); - when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false))) - .thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[1]); - - } - }); - when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(EnumMap.class))).thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[0]); - - } - }); - when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return Either.left((Resource) args[0]); - - } - }); - - Either either = Either.left(true); - when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); - } - - public ResponseFormat createGeneralErrorInfo() { - ResponseFormat responseFormat = new ResponseFormat(500); - responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); - return responseFormat; - } - - private UploadResourceInfo createDummyResourceMD() { - UploadResourceInfo resourceMD = new UploadResourceInfo(); - resourceMD.setName("tosca.nodes.BlockStorage"); - resourceMD.setPayloadName("payLoad"); - resourceMD.addSubCategory("Generic", "Infrastructure"); - resourceMD.setContactId("ya107f"); - resourceMD.setResourceIconPath("defaulticon"); - resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); - resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); - return resourceMD; - } - - private void testSetProperties(Resource resource) { - List propertiesList = resource.getProperties(); - - Map properties = new HashMap(); - for (PropertyDefinition propertyDefinition : propertiesList) { - properties.put(propertyDefinition.getName(), propertyDefinition); - } - - assertTrue(properties.size() == 3); - assertTrue(properties.containsKey("size")); - PropertyDefinition propertyDefinition = properties.get("size"); - assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); - assertTrue(propertyDefinition.getConstraints().size() == 1); - PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); - assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); - - assertTrue(properties.containsKey("volume_id")); - propertyDefinition = properties.get("volume_id"); - assertTrue(propertyDefinition.getType().equals("string")); - assertTrue(propertyDefinition.isRequired() == false); - - assertTrue(properties.containsKey("snapshot_id")); - propertyDefinition = properties.get("snapshot_id"); - assertTrue(propertyDefinition.getType().equals("string")); - assertTrue(propertyDefinition.isRequired() == false); - - } - - private void testSetCapabilities(Resource resource) { - Map> capabilities = resource.getCapabilities(); - assertTrue(capabilities.size() == 3); - assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); - List capabilityList = capabilities.get("tosca.capabilities.Endpoint"); - CapabilityDefinition capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); - assertTrue(capability.getName().equals("data_endpoint")); - - assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); - capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); - capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); - assertTrue(capability.getName().equals("admin_endpoint")); - - assertTrue(capabilities.containsKey("tosca.capabilities.Container")); - capabilityList = capabilities.get("tosca.capabilities.Container"); - capability = capabilityList.get(0); - assertTrue(capability.getType().equals("tosca.capabilities.Container")); - assertTrue(capability.getName().equals("host")); - - List validSourceTypes = capability.getValidSourceTypes(); - assertTrue(validSourceTypes.size() == 1); - assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); - - } - - private void testSetRequirments(Resource resource) { - Map> requirements = resource.getRequirements(); - assertTrue(requirements.size() == 2); - - assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); - List requirementList = requirements.get("tosca.capabilities.network.Linkable"); - RequirementDefinition requirement = requirementList.get(0); - assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); - assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); - assertTrue(requirement.getName().equals("link")); - - assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); - requirementList = requirements.get("tosca.capabilities.network.Bindable"); - requirement = requirementList.get(0); - assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); - assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); - assertTrue(requirement.getName().equals("binding")); - - } - - private void testSetDerivedFrom(Resource resource) { - assertTrue(resource.getDerivedFrom().size() == 1); - assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); - - } - - private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { - - // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) - // ); - assertTrue(resource.getDescription().equals(resourceMD.getDescription())); - assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); - assertTrue(resource.getName().equals(resourceMD.getName())); - - assertTrue(resource.getContactId().equals(resourceMD.getContactId())); - assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); - - // assertTrue( resource.isAbstract() == - // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); - - assertTrue(resourceMD.getTags().size() == resource.getTags().size()); - for (String tag : resource.getTags()) { - assertTrue(resourceMD.getTags().contains(tag)); - } - - } - - private void testSetConstantMetaData(Resource resource) { - assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); - assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); - assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); - assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); - assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); - } + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + + testSetConstantMetaData(resource); + testSetMetaDataFromJson(resource, resourceMD); + + testSetDerivedFrom(resource); + testSetProperties(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + } + + @Test + public void testResourceCreationFailed() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + ResponseFormat dummyResponseFormat = createGeneralErrorInfo(); + + when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat); + setResourceBusinessLogicMock(); + + String jsonContent = "this is an invalid yml!"; + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isRight()); + ResponseFormat errorInfoFromTest = createResource.right().value(); + assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus())); + assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId())); + assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage())); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)); + + Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + + } + + @Test + public void testResourceCreationWithCapabilities() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"); + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + Resource resource = createResource.left().value().left; + testSetCapabilities(resource); + + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)); + Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false); + + } + + @Test + public void testResourceCreationWithRequirments() throws IOException { + UploadResourceInfo resourceMD = createDummyResourceMD(); + User user = new User(); + user.setUserId(resourceMD.getContactId()); + Either eitherUser = Either.left(user); + + when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser); + + setResourceBusinessLogicMock(); + + String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml"); + + Either, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true); + assertTrue(createResource.isLeft()); + testSetRequirments(createResource.left().value().left); + + } + + private void setResourceBusinessLogicMock() { + when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin); + when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false))) + .thenAnswer(new Answer, ResponseFormat>>() { + public Either, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left(new ImmutablePair((Resource) args[0], ActionStatus.CREATED)); + + } + }); + when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false))) + .thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[1]); + + } + }); + when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return Either.left((Resource) args[0]); + + } + }); + + Either either = Either.left(true); + when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either); + } + + public ResponseFormat createGeneralErrorInfo() { + ResponseFormat responseFormat = new ResponseFormat(500); + responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null)); + return responseFormat; + } + + private UploadResourceInfo createDummyResourceMD() { + UploadResourceInfo resourceMD = new UploadResourceInfo(); + resourceMD.setName("tosca.nodes.BlockStorage"); + resourceMD.setPayloadName("payLoad"); + resourceMD.addSubCategory("Generic", "Infrastructure"); + resourceMD.setContactId("ya107f"); + resourceMD.setResourceIconPath("defaulticon"); + resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" })); + resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created."); + resourceMD.setResourceVendorModelNumber("vendorReleaseNumber"); + return resourceMD; + } + + private void testSetProperties(Resource resource) { + List propertiesList = resource.getProperties(); + + Map properties = new HashMap(); + for (PropertyDefinition propertyDefinition : propertiesList) { + properties.put(propertyDefinition.getName(), propertyDefinition); + } + + assertTrue(properties.size() == 3); + assertTrue(properties.containsKey("size")); + PropertyDefinition propertyDefinition = properties.get("size"); + assertTrue(propertyDefinition.getType().equals("scalar-unit.size")); + assertTrue(propertyDefinition.getConstraints().size() == 1); + PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0); + assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint); + + assertTrue(properties.containsKey("volume_id")); + propertyDefinition = properties.get("volume_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + assertTrue(properties.containsKey("snapshot_id")); + propertyDefinition = properties.get("snapshot_id"); + assertTrue(propertyDefinition.getType().equals("string")); + assertTrue(propertyDefinition.isRequired() == false); + + } + + private void testSetCapabilities(Resource resource) { + Map> capabilities = resource.getCapabilities(); + assertTrue(capabilities.size() == 3); + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint")); + List capabilityList = capabilities.get("tosca.capabilities.Endpoint"); + CapabilityDefinition capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint")); + assertTrue(capability.getName().equals("data_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin")); + capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin")); + assertTrue(capability.getName().equals("admin_endpoint")); + + assertTrue(capabilities.containsKey("tosca.capabilities.Container")); + capabilityList = capabilities.get("tosca.capabilities.Container"); + capability = capabilityList.get(0); + assertTrue(capability.getType().equals("tosca.capabilities.Container")); + assertTrue(capability.getName().equals("host")); + + List validSourceTypes = capability.getValidSourceTypes(); + assertTrue(validSourceTypes.size() == 1); + assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication")); + + } + + private void testSetRequirments(Resource resource) { + Map> requirements = resource.getRequirements(); + assertTrue(requirements.size() == 2); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable")); + List requirementList = requirements.get("tosca.capabilities.network.Linkable"); + RequirementDefinition requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo")); + assertTrue(requirement.getName().equals("link")); + + assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable")); + requirementList = requirements.get("tosca.capabilities.network.Bindable"); + requirement = requirementList.get(0); + assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable")); + assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo")); + assertTrue(requirement.getName().equals("binding")); + + } + + private void testSetDerivedFrom(Resource resource) { + assertTrue(resource.getDerivedFrom().size() == 1); + assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root")); + + } + + private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) { + + // assertTrue( resource.getCategory().equals(resourceMD.getCategory()) + // ); + assertTrue(resource.getDescription().equals(resourceMD.getDescription())); + assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath())); + assertTrue(resource.getName().equals(resourceMD.getName())); + assertEquals(resource.getResourceVendorModelNumber(), resourceMD.getResourceVendorModelNumber()); + assertTrue(resource.getContactId().equals(resourceMD.getContactId())); + assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId())); + + // assertTrue( resource.isAbstract() == + // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory())); + + assertTrue(resourceMD.getTags().size() == resource.getTags().size()); + for (String tag : resource.getTags()) { + assertTrue(resourceMD.getTags().contains(tag)); + } + + } + + private void testSetConstantMetaData(Resource resource) { + assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION)); + assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE); + assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION); + assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME)); + assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE)); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java index 9a8f1c5ad8..e750d3ab51 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java @@ -20,71 +20,71 @@ package org.openecomp.sdc.be.components; -import java.util.ArrayList; -import java.util.List; - import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; +import java.util.ArrayList; +import java.util.List; + public class ResourceTestUtils { - public static Resource prepareResource(int resourceIndex) { - Resource r = new Resource(); - r.setName("resource_" + resourceIndex); - r.setDescription("description"); - r.setVendorName("vendor name"); - r.setVendorRelease("vendor release"); - r.setContactId("as123y"); - r.addCategory("Generic", "Infrastructure"); - List arr = new ArrayList(); - arr.add("tosca.nodes.Root"); - r.setDerivedFrom(arr); - List arr1 = new ArrayList(); - arr1.add(r.getName()); - r.setTags(arr1); - r.setIcon("borderElement"); - return r; - } + public static Resource prepareResource(int resourceIndex) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.addCategory("Generic", "Infrastructure"); + List arr = new ArrayList(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List arr1 = new ArrayList(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } - public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { - Resource r = new Resource(); - r.setName("resource_" + resourceIndex); - r.setToscaResourceName("resource_" + resourceIndex); - r.setDescription("description"); - r.setVendorName("vendor name"); - r.setVendorRelease("vendor release"); - r.setContactId("as123y"); - r.setResourceType(resourceType); - r.addCategory("Generic", "Infrastructure"); - List arr = new ArrayList(); - arr.add("tosca.nodes.Root"); - r.setDerivedFrom(arr); - List arr1 = new ArrayList(); - arr1.add(r.getName()); - r.setTags(arr1); - r.setIcon("borderElement"); - return r; - } + public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) { + Resource r = new Resource(); + r.setName("resource_" + resourceIndex); + r.setToscaResourceName("resource_" + resourceIndex); + r.setDescription("description"); + r.setVendorName("vendor name"); + r.setVendorRelease("vendor release"); + r.setContactId("as123y"); + r.setResourceType(resourceType); + r.addCategory("Generic", "Infrastructure"); + List arr = new ArrayList(); + arr.add("tosca.nodes.Root"); + r.setDerivedFrom(arr); + List arr1 = new ArrayList(); + arr1.add(r.getName()); + r.setTags(arr1); + r.setIcon("borderElement"); + return r; + } - public static Service prepareService(int serviceIndex) { - Service service = new Service(); - service.setName("service_" + serviceIndex); - service.setDescription("desc"); - service.setIcon("icon-service-red1"); - List tags = new ArrayList(); - tags.add(service.getName()); - service.setTags(tags); - CategoryDefinition category = new CategoryDefinition(); - category.setName("Mobility"); - List categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - service.setContactId("as123y"); - service.setProjectCode("123456"); + public static Service prepareService(int serviceIndex) { + Service service = new Service(); + service.setName("service_" + serviceIndex); + service.setDescription("desc"); + service.setIcon("icon-service-red1"); + List tags = new ArrayList(); + tags.add(service.getName()); + service.setTags(tags); + CategoryDefinition category = new CategoryDefinition(); + category.setName("Mobility"); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + service.setContactId("as123y"); + service.setProjectCode("123456"); - return service; - } + return service; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java index 1af1ac3070..bbb381bad3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java @@ -20,31 +20,19 @@ package org.openecomp.sdc.be.components; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; @@ -83,940 +71,881 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; - -public class ServiceBusinessLogicTest { - - private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName()); - private static final String SERVICE_CATEGORY = "Mobility"; - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - ServiceBusinessLogic bl = new ServiceBusinessLogic(); - ResponseFormatManager responseManager = null; - IElementOperation mockElementDao; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - ComponentsUtils componentsUtils = new ComponentsUtils(); - AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); - ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - - User user = null; - Service serviceResponse = null; - Resource genericService = null; - - private static final String CERTIFIED_VERSION = "1.0"; - private static final String UNCERTIFIED_VERSION = "0.2"; - private static final String COMPONNET_ID = "myUniqueId"; - private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; - private static Map FILTER_MAP_CERTIFIED_VERSION = new HashMap(); - private static Map FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap(); - private static Map FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap(); - - public ServiceBusinessLogicTest() { - - } - - @Before - public void setup() { - - ExternalConfiguration.setAppName("catalog-be"); - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); -// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); - - // artifact bussinesslogic - ArtifactDefinition artifactDef = new ArtifactDefinition(); - when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); - - // createService - serviceResponse = createServiceObject(true); - Either eitherCreate = Either.left(serviceResponse); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); - Either eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); - Either eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); - - genericService = setupGenericServiceMock(); - Either findLatestGeneric = Either.left(genericService); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); - - - bl = new ServiceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setArtifactBl(artifactBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setCassandraAuditingDao(auditingDao); - bl.setCacheManagerOperation(cacheManager); - - mockAuditingDaoLogic(); - - responseManager = ResponseFormatManager.getInstance(); - - } - - @Test - public void testGetComponentAuditRecordsCertifiedVersion() { - Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); - assertTrue(componentAuditRecords.isLeft()); - int size = componentAuditRecords.left().value().size(); - assertTrue(size == 3); - } - - @Test - public void testGetComponentAuditRecordsUnCertifiedVersion() { - Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); - assertTrue(componentAuditRecords.isLeft()); - int size = componentAuditRecords.left().value().size(); - assertTrue(size == 1); - } - - @Test - public void testHappyScenario() { - Service service = createServiceObject(false); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); - Either createResponse = bl.createService(service, user); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); - } - - private void assertEqualsServiceObject(Service origService, Service newService) { - assertEquals(origService.getContactId(), newService.getContactId()); - assertEquals(origService.getCategories(), newService.getCategories()); - assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); - assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); - assertEquals(origService.getDescription(), newService.getDescription()); - assertEquals(origService.getIcon(), newService.getIcon()); - assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); - assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); - assertEquals(origService.getName(), newService.getName()); - assertEquals(origService.getName(), newService.getName()); - assertEquals(origService.getUniqueId(), newService.getUniqueId()); - assertEquals(origService.getVersion(), newService.getVersion()); - assertEquals(origService.getArtifacts(), newService.getArtifacts()); - assertEquals(origService.getCreationDate(), newService.getCreationDate()); - assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); - assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); - assertEquals(origService.getTags(), newService.getTags()); - } - - private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - /* CREATE validations - start ***********************/ - // Service name - start - - @Test - public void testFailedServiceValidations() { - testServiceNameAlreadyExists(); - testServiceNameEmpty(); - // testServiceNameExceedsLimit(); - testServiceNameWrongFormat(); - testServiceDescriptionEmpty(); - testServiceDescriptionMissing(); - testServiceDescExceedsLimitCreate(); - testServiceDescNotEnglish(); - testServiceIconEmpty(); - testServiceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - // testTagsExceedsLimitCreate(); - // testTagsSingleExcessLimit(); - testTagsNoServiceName(); - testInvalidTag(); - testServiceTagNotExist(); - testServiceTagEmpty(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testInvalidProjectCode(); - testProjectCodeTooLong(); - testProjectCodeTooShort(); - - testResourceContactIdMissing(); - testServiceCategoryExist(); - testServiceBadCategoryCreate(); - testMissingProjectCode(); - } - - private void testServiceNameAlreadyExists() { - String serviceName = "alreadyExist"; - Service serviceExccedsNameLimit = createServiceObject(false); - // 51 chars, the limit is 50 - serviceExccedsNameLimit.setName(serviceName); - List tgs = new ArrayList(); - tgs.add(serviceName); - serviceExccedsNameLimit.setTags(tgs); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); - } - - private void testServiceNameEmpty() { - Service serviceExccedsNameLimit = createServiceObject(false); - serviceExccedsNameLimit.setName(null); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceNameExceedsLimit() { - Service serviceExccedsNameLimit = createServiceObject(false); - // 51 chars, the limit is 50 - String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse"; - serviceExccedsNameLimit.setName(tooLongServiceName); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testServiceNameWrongFormat() { - Service service = createServiceObject(false); - // contains : - String nameWrongFormat = "ljg\fd"; - service.setName(nameWrongFormat); - - Either createResponse = bl.createService(service, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service name - end - // Service description - start - private void testServiceDescriptionEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setDescription(""); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceDescriptionMissing() { - Service serviceExist = createServiceObject(false); - serviceExist.setDescription(null); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceDescExceedsLimitCreate() { - Service serviceExccedsDescLimit = createServiceObject(false); - // 1025 chars, the limit is 1024 - String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - serviceExccedsDescLimit.setDescription(tooLongServiceDesc); - - Either createResponse = bl.createService(serviceExccedsDescLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testServiceDescNotEnglish() { - Service notEnglish = createServiceObject(false); - // Not english - String tooLongServiceDesc = "\uC2B5"; - notEnglish.setDescription(tooLongServiceDesc); - - Either createResponse = bl.createService(notEnglish, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service description - stop - // Service icon - start - private void testServiceIconEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setIcon(""); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testServiceIconMissing() { - Service serviceExist = createServiceObject(false); - serviceExist.setIcon(null); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceIconInvalid() { - Service resourceExist = createServiceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Service resourceExist = createServiceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Service icon - stop - // Service tags - start - private void testTagsExceedsLimitCreate() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List tagsList = new ArrayList(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(serviceExccedsNameLimit.getName()); - - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExcessLimit() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a"; - String tag2 = serviceExccedsNameLimit.getName(); - List tagsList = new ArrayList(); - tagsList.add(tag1); - tagsList.add(tag2); - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb"; - List tagsList = new ArrayList(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Service serviceExccedsNameLimit = createServiceObject(false); - String tag1 = "afzs2qLBb%#%"; - List tagsList = new ArrayList(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createService(serviceExccedsNameLimit, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); - - } - - private void testServiceTagNotExist() { - Service serviceExist = createServiceObject(false); - serviceExist.setTags(null); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testServiceTagEmpty() { - Service serviceExist = createServiceObject(false); - serviceExist.setTags(new ArrayList()); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - // Service tags - stop - // Service contactId - start - private void testContactIdTooLong() { - Service serviceContactId = createServiceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - serviceContactId.setContactId(contactIdTooLong); - - Either createResponse = bl.createService(serviceContactId, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Service serviceContactId = createServiceObject(false); - // 3 letters and 3 digits and special characters - String contactIdTooLong = "yrt134!!!"; - serviceContactId.setContactId(contactIdTooLong); - - Either createResponse = bl.createService(serviceContactId, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - private void testResourceContactIdMissing() { - Service resourceExist = createServiceObject(false); - resourceExist.setContactId(null); - - Either createResponse = bl.createService(resourceExist, user); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); - } - - // Service contactId - stop - // Service category - start - private void testServiceCategoryExist() { - Service serviceExist = createServiceObject(false); - serviceExist.setCategories(null); - - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - } +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; - public void markDistributionAsDeployedTestAlreadyDeployed() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String resultAction = "DResult"; - String did = "123456"; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; - setupBeforeDeploy(notifyAction, requestAction, did); - List resultList = new ArrayList(); - Map params = new HashMap(); - DistributionDeployEvent event = new DistributionDeployEvent(); +public class ServiceBusinessLogicTest { - event.setAction(resultAction); - event.setDid(did); - event.setStatus("200"); - // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); - // deployEvent.setFields(params); - resultList.add(event); - Either, ActionStatus> eventList = Either.left(resultList); + private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class); + private static final String SERVICE_CATEGORY = "Mobility"; + final ServletContext servletContext = Mockito.mock(ServletContext.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + ResponseFormatManager responseManager = null; + IElementOperation mockElementDao; + ComponentsUtils componentsUtils; + AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class); + ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class); + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + + User user = null; + Service serviceResponse = null; + Resource genericService = null; + + private static final String CERTIFIED_VERSION = "1.0"; + private static final String UNCERTIFIED_VERSION = "0.2"; + private static final String COMPONNET_ID = "myUniqueId"; + private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + private static Map FILTER_MAP_CERTIFIED_VERSION = new HashMap(); + private static Map FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap(); + private static Map FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap(); + + public ServiceBusinessLogicTest() { + + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); +// when(userValidations.validateUserRole(user)) + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); +// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation()); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK); + + // artifact bussinesslogic + ArtifactDefinition artifactDef = new ArtifactDefinition(); + when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef); + + // createService + serviceResponse = createServiceObject(true); + Either eitherCreate = Either.left(serviceResponse); + when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate); + Either eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount); + Either eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist); + + genericService = setupGenericServiceMock(); + Either findLatestGeneric = Either.left(genericService); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric); + + + bl = new ServiceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setArtifactBl(artifactBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + bl.setComponentsUtils(componentsUtils); + bl.setCassandraAuditingDao(auditingDao); + bl.setCacheManagerOperation(cacheManager); + bl.setUserValidations(userValidations); + + mockAuditingDaoLogic(); + + responseManager = ResponseFormatManager.getInstance(); + + } + + @Test + public void testGetComponentAuditRecordsCertifiedVersion() { + Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 3); + } + + @Test + public void testGetComponentAuditRecordsUnCertifiedVersion() { + Either>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId()); + assertTrue(componentAuditRecords.isLeft()); + int size = componentAuditRecords.left().value().size(); + assertTrue(size == 1); + } + + @Test + public void testHappyScenario() { + Service service = createServiceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService)); + Either createResponse = bl.createService(service, user); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEqualsServiceObject(createServiceObject(true), createResponse.left().value()); + } + + private void validateUserRoles(Role ... roles) { + List listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + private void assertEqualsServiceObject(Service origService, Service newService) { + assertEquals(origService.getContactId(), newService.getContactId()); + assertEquals(origService.getCategories(), newService.getCategories()); + assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId()); + assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName()); + assertEquals(origService.getDescription(), newService.getDescription()); + assertEquals(origService.getIcon(), newService.getIcon()); + assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId()); + assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getName(), newService.getName()); + assertEquals(origService.getUniqueId(), newService.getUniqueId()); + assertEquals(origService.getVersion(), newService.getVersion()); + assertEquals(origService.getArtifacts(), newService.getArtifacts()); + assertEquals(origService.getCreationDate(), newService.getCreationDate()); + assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate()); + assertEquals(origService.getLifecycleState(), newService.getLifecycleState()); + assertEquals(origService.getTags(), newService.getTags()); + } + + private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + /* CREATE validations - start ***********************/ + // Service name - start + + @Test + public void testFailedServiceValidations() { + testServiceNameAlreadyExists(); + testServiceNameEmpty(); + // testServiceNameExceedsLimit(); + testServiceNameWrongFormat(); + testServiceDescriptionEmpty(); + testServiceDescriptionMissing(); + testServiceDescExceedsLimitCreate(); + testServiceDescNotEnglish(); + testServiceIconEmpty(); + testServiceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + // testTagsExceedsLimitCreate(); + // testTagsSingleExcessLimit(); + testTagsNoServiceName(); + testInvalidTag(); + testServiceTagNotExist(); + testServiceTagEmpty(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testInvalidProjectCode(); + testProjectCodeTooLong(); + testProjectCodeTooShort(); + + testResourceContactIdMissing(); + testServiceCategoryExist(); + testServiceBadCategoryCreate(); + testMissingProjectCode(); + } + + private void testServiceNameAlreadyExists() { + String serviceName = "alreadyExist"; + Service serviceExccedsNameLimit = createServiceObject(false); + // 51 chars, the limit is 50 + serviceExccedsNameLimit.setName(serviceName); + List tgs = new ArrayList(); + tgs.add(serviceName); + serviceExccedsNameLimit.setTags(tgs); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName); + } + + private void testServiceNameEmpty() { + Service serviceExccedsNameLimit = createServiceObject(false); + serviceExccedsNameLimit.setName(null); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceNameWrongFormat() { + Service service = createServiceObject(false); + // contains : + String nameWrongFormat = "ljg\fd"; + service.setName(nameWrongFormat); + + Either createResponse = bl.createService(service, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service name - end + // Service description - start + private void testServiceDescriptionEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(""); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescriptionMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setDescription(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceDescExceedsLimitCreate() { + Service serviceExccedsDescLimit = createServiceObject(false); + // 1025 chars, the limit is 1024 + String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + serviceExccedsDescLimit.setDescription(tooLongServiceDesc); + + Either createResponse = bl.createService(serviceExccedsDescLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testServiceDescNotEnglish() { + Service notEnglish = createServiceObject(false); + // Not english + String tooLongServiceDesc = "\uC2B5"; + notEnglish.setDescription(tooLongServiceDesc); + + Either createResponse = bl.createService(notEnglish, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service description - stop + // Service icon - start + private void testServiceIconEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(""); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testServiceIconMissing() { + Service serviceExist = createServiceObject(false); + serviceExist.setIcon(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconInvalid() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Service resourceExist = createServiceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + private void testTagsNoServiceName() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Service serviceExccedsNameLimit = createServiceObject(false); + String tag1 = "afzs2qLBb%#%"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createService(serviceExccedsNameLimit, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" }); + + } + + private void testServiceTagNotExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testServiceTagEmpty() { + Service serviceExist = createServiceObject(false); + serviceExist.setTags(new ArrayList()); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + // Service tags - stop + // Service contactId - start + private void testContactIdTooLong() { + Service serviceContactId = createServiceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + serviceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Service serviceContactId = createServiceObject(false); + // 3 letters and 3 digits and special characters + String contactIdTooLong = "yrt134!!!"; + serviceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createService(serviceContactId, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + private void testResourceContactIdMissing() { + Service resourceExist = createServiceObject(false); + resourceExist.setContactId(null); + + Either createResponse = bl.createService(resourceExist, user); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue()); + } + + // Service contactId - stop + // Service category - start + private void testServiceCategoryExist() { + Service serviceExist = createServiceObject(false); + serviceExist.setCategories(null); + + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } + + public void markDistributionAsDeployedTestAlreadyDeployed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String resultAction = "DResult"; + String did = "123456"; - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); + setupBeforeDeploy(notifyAction, requestAction, did); + List resultList = new ArrayList(); + Map params = new HashMap(); + DistributionDeployEvent event = new DistributionDeployEvent(); - Either markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + event.setAction(resultAction); + event.setDid(did); + event.setStatus("200"); + // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent(); + // deployEvent.setFields(params); + resultList.add(event); + Either, ActionStatus> eventList = Either.left(resultList); - Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList); - } + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); - @Test - public void markDistributionAsDeployedTestSuccess() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String did = "123456"; + Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction); - setupBeforeDeploy(notifyAction, requestAction, did); + } - Either markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isLeft()); + @Test + public void markDistributionAsDeployedTestSuccess() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; - } + setupBeforeDeploy(notifyAction, requestAction, did); + List roles = new ArrayList<>(); + roles.add(Role.ADMIN); + roles.add(Role.OPS); + when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true)); + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isLeft()); + } - @Test - public void markDistributionAsDeployedTestNotDistributed() { - String notifyAction = "DNotify"; - String requestAction = "DRequest"; - String did = "123456"; + //@Test + public void markDistributionAsDeployedTestNotDistributed() { + String notifyAction = "DNotify"; + String requestAction = "DRequest"; + String did = "123456"; - setupBeforeDeploy(notifyAction, requestAction, did); - List emptyList = new ArrayList(); - Either, ActionStatus> emptyEventList = Either.left(emptyList); - Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); + setupBeforeDeploy(notifyAction, requestAction, did); + List emptyList = new ArrayList(); + Either, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList); - Either notFound = Either.right(StorageOperationStatus.NOT_FOUND); - Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); + Either notFound = Either.right(StorageOperationStatus.NOT_FOUND); + Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound); - Either markDeployed = bl.markDistributionAsDeployed(did, did, user); - assertTrue(markDeployed.isRight()); - assertEquals(404, markDeployed.right().value().getStatus().intValue()); + Either markDeployed = bl.markDistributionAsDeployed(did, did, user); + assertTrue(markDeployed.isRight()); + assertEquals(404, markDeployed.right().value().getStatus().intValue()); - } + } - private void testServiceBadCategoryCreate() { + private void testServiceBadCategoryCreate() { - Service serviceExist = createServiceObject(false); - CategoryDefinition category = new CategoryDefinition(); - category.setName("koko"); - List categories = new ArrayList<>(); - categories.add(category); - serviceExist.setCategories(categories); + Service serviceExist = createServiceObject(false); + CategoryDefinition category = new CategoryDefinition(); + category.setName("koko"); + List categories = new ArrayList<>(); + categories.add(category); + serviceExist.setCategories(categories); - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); - } + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()); + } - // Service category - stop - // Service projectCode - start - private void testInvalidProjectCode() { + // Service category - stop + // Service projectCode - start + private void testInvalidProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("koko!!"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("koko!!"); - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooLong() { + private void testProjectCodeTooLong() { - Service serviceExist = createServiceObject(false); - String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; - serviceExist.setProjectCode(tooLongProjectCode); + Service serviceExist = createServiceObject(false); + String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode"; + serviceExist.setProjectCode(tooLongProjectCode); - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testProjectCodeTooShort() { + private void testProjectCodeTooShort() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode("333"); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode("333"); - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE); + } - private void testMissingProjectCode() { + private void testMissingProjectCode() { - Service serviceExist = createServiceObject(false); - serviceExist.setProjectCode(null); + Service serviceExist = createServiceObject(false); + serviceExist.setProjectCode(null); - Either createResponse = bl.createService(serviceExist, user); - assertTrue(createResponse.isRight()); + Either createResponse = bl.createService(serviceExist, user); + assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); - } + assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE); + } -// @Test -// public void testDeleteMarkedServicesNoServices() { -// List ids = new ArrayList(); -// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// @Test +// public void testDeleteMarkedServicesNoServices() { +// List ids = new ArrayList(); +// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// } - - @Test - @Ignore - public void testDeleteMarkedServices() { - List ids = new ArrayList(); - String resourceInUse = "123"; - ids.add(resourceInUse); - String resourceFree = "456"; - ids.add(resourceFree); - Either, StorageOperationStatus> eitherNoResources = Either.left(ids); - when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); - - Either resourceInUseResponse = Either.left(true); - Either resourceFreeResponse = Either.left(false); - - List artifacts = new ArrayList(); - Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); - - when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); - when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); - - Either eitherDelete = Either.left(new Resource()); - when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); - - Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); - assertTrue(deleteMarkedResources.isLeft()); - List resourceIdList = deleteMarkedResources.left().value(); - assertFalse(resourceIdList.isEmpty()); - assertTrue(resourceIdList.contains(resourceFree)); - assertFalse(resourceIdList.contains(resourceInUse)); - - } - - private Service createServiceObject(boolean afterCreate) { - Service service = new Service(); - service.setName("Service"); - CategoryDefinition category = new CategoryDefinition(); - category.setName(SERVICE_CATEGORY); - List categories = new ArrayList<>(); - categories.add(category); - service.setCategories(categories); - - service.setDescription("description"); - List tgs = new ArrayList(); - tgs.add(service.getName()); - service.setTags(tgs); - // service.setVendorName("Motorola"); - // service.setVendorRelease("1.0.0"); - service.setIcon("MyIcon"); - // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - service.setContactId("aa1234"); - service.setProjectCode("12345"); - - if (afterCreate) { - service.setVersion("0.1"); - service.setUniqueId(service.getName() + ":" + service.getVersion()); - service.setCreatorUserId(user.getUserId()); - service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - } - return service; - } - - private void mockAuditingDaoLogic() { - FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); - - FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); - FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); - - final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); - createResourceAudit.setModifier("Carlos Santana(cs0008)"); - createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); - createResourceAudit.setCurrVersion("0.1"); - createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); - createResourceAudit.setDesc("OK"); - createResourceAudit.setResourceType("Resource"); - createResourceAudit.setStatus("201"); - createResourceAudit.setPrevVersion(""); - createResourceAudit.setAction("Create"); - // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); - createResourceAudit.setPrevState(""); - createResourceAudit.setResourceName("MyTestResource"); - // createResourceAudit.setFields(fields); - - final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); - checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); - checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); - checkInResourceAudit.setCurrVersion("0.1"); - checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); - checkInResourceAudit.setDesc("OK"); - checkInResourceAudit.setComment("Stam"); - checkInResourceAudit.setResourceType("Resource"); - checkInResourceAudit.setStatus("200"); - checkInResourceAudit.setPrevVersion("0.1"); - checkInResourceAudit.setAction("Checkin"); - // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); - checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); - checkInResourceAudit.setResourceName("MyTestResource"); - - final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); - checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); - checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); - checkOutResourceAudit.setCurrVersion("0.2"); - checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); - checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); - checkOutResourceAudit.setDesc("OK"); - checkOutResourceAudit.setComment(""); - checkOutResourceAudit.setResourceType("Resource"); - checkOutResourceAudit.setStatus("200"); - checkOutResourceAudit.setPrevVersion("0.1"); - checkOutResourceAudit.setAction("Checkout"); - // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); - checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); - checkOutResourceAudit.setResourceName("MyTestResource"); - // checkOutResourceAudit.setFields(fields); - - // Mockito.doAnswer(new Answer, - // ActionStatus> >() { - // public Either, ActionStatus> - // answer(InvocationOnMock invocation) { - // final Either, ActionStatus> either; - // final List list; - // Object[] args = invocation.getArguments(); - // Map filterMap = - // (Map) args[0]; - // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ - // list = new - // ArrayList(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; - // either = Either.left(list); - // - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ - // list = new ArrayList(); - // either = Either.left(list); - // } - // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ - // list = new - // ArrayList(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; - // either = Either.left(list); - // } - // else{ - // either = null; - // } - // return either; - // } - // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); - // - // - List list = new ArrayList() { - { - add(createResourceAudit); - add(checkInResourceAudit); - add(checkOutResourceAudit); - } - }; - Either, ActionStatus> result = Either.left(list); - Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); - - List listPrev = new ArrayList(); - Either, ActionStatus> resultPrev = Either.left(listPrev); - Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); - - List listCurr = new ArrayList() { - { - add(checkOutResourceAudit); - } - }; - Either, ActionStatus> resultCurr = Either.left(listCurr); - Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); - - } - - private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { - - DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); - notifyEvent.setAction(notifyAction); - notifyEvent.setDid(did); - notifyEvent.setStatus("200"); - - ResourceAdminEvent requestEvent = new ResourceAdminEvent(); - requestEvent.setAction(requestAction); - requestEvent.setDid(did); - requestEvent.setStatus("200"); - - ArrayList arrayList = new ArrayList(); - List notifyResults = arrayList; - notifyResults.add(notifyEvent); - Either, ActionStatus> eitherNotify = Either.left(notifyResults); - - Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); - - List requestResults = new ArrayList(); - requestResults.add(requestEvent); - Either, ActionStatus> eitherRequest = Either.left(requestResults); - Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); - - Either eitherService = Either.left(createServiceObject(true)); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); - - List emptyList = new ArrayList(); - Either, ActionStatus> emptyEventList = Either.left(emptyList); - Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testFindGroupInstanceOnRelatedComponentInstance() { - - Class targetClass = ServiceBusinessLogic.class; - String methodName = "findGroupInstanceOnRelatedComponentInstance"; - Object invalidId = "invalidId"; - - Component service = createNewService(); - List componentInstances = service.getComponentInstances(); - - Either, ResponseFormat> findGroupInstanceRes; - Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - Class[] argClasses = {Component.class, String.class,String.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - - findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); - assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); - - Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; - - findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); - - Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; - - findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); - assertTrue(findGroupInstanceRes != null); - assertTrue(findGroupInstanceRes.isRight()); - assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - private Component createNewService() { - - Service service = new Service(); - int listSize = 3; - service.setName("serviceName"); - service.setUniqueId("serviceUniqueId"); - List componentInstances = new ArrayList<>(); - ComponentInstance ci; - for(int i= 0; i groupInstances= new ArrayList<>(); - GroupInstance gi; - for(int j = 0; j createResponse = bl.createService(service, user); - assertTrue(createResponse.isLeft()); - service = createResponse.left().value(); - assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); - assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); - } - - - private Resource setupGenericServiceMock(){ - Resource genericService = new Resource(); - genericService.setVersion("1.0"); - genericService.setToscaResourceName(GENERIC_SERVICE_NAME); - return genericService; - } +// } + + @Test + @Ignore + public void testDeleteMarkedServices() { + List ids = new ArrayList(); + String resourceInUse = "123"; + ids.add(resourceInUse); + String resourceFree = "456"; + ids.add(resourceFree); + Either, StorageOperationStatus> eitherNoResources = Either.left(ids); + when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + + Either resourceInUseResponse = Either.left(true); + Either resourceFreeResponse = Either.left(false); + + List artifacts = new ArrayList(); + Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse); + + when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); + when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); + + Either eitherDelete = Either.left(new Resource()); + when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); + + Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); + assertTrue(deleteMarkedResources.isLeft()); + List resourceIdList = deleteMarkedResources.left().value(); + assertFalse(resourceIdList.isEmpty()); + assertTrue(resourceIdList.contains(resourceFree)); + assertFalse(resourceIdList.contains(resourceInUse)); + + } + + private Service createServiceObject(boolean afterCreate) { + Service service = new Service(); + service.setUniqueId("sid"); + service.setName("Service"); + CategoryDefinition category = new CategoryDefinition(); + category.setName(SERVICE_CATEGORY); + List categories = new ArrayList<>(); + categories.add(category); + service.setCategories(categories); + + service.setDescription("description"); + List tgs = new ArrayList(); + tgs.add(service.getName()); + service.setTags(tgs); + // service.setVendorName("Motorola"); + // service.setVendorRelease("1.0.0"); + service.setIcon("MyIcon"); + // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setContactId("aa1234"); + service.setProjectCode("12345"); + + if (afterCreate) { + service.setVersion("0.1"); + service.setUniqueId(service.getName() + ":" + service.getVersion()); + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + } + return service; + } + + private void mockAuditingDaoLogic() { + FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID); + + FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION); + FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION); + + final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent(); + createResourceAudit.setModifier("Carlos Santana(cs0008)"); + createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + createResourceAudit.setCurrVersion("0.1"); + createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f"); + createResourceAudit.setDesc("OK"); + createResourceAudit.setResourceType("Resource"); + createResourceAudit.setStatus("201"); + createResourceAudit.setPrevVersion(""); + createResourceAudit.setAction("Create"); + // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977"); + createResourceAudit.setPrevState(""); + createResourceAudit.setResourceName("MyTestResource"); + // createResourceAudit.setFields(fields); + + final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent(); + checkInResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN"); + checkInResourceAudit.setCurrVersion("0.1"); + checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091"); + checkInResourceAudit.setDesc("OK"); + checkInResourceAudit.setComment("Stam"); + checkInResourceAudit.setResourceType("Resource"); + checkInResourceAudit.setStatus("200"); + checkInResourceAudit.setPrevVersion("0.1"); + checkInResourceAudit.setAction("Checkin"); + // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797"); + checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT"); + checkInResourceAudit.setResourceName("MyTestResource"); + + final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent(); + checkOutResourceAudit.setModifier("Carlos Santana(cs0008)"); + checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT"); + checkOutResourceAudit.setCurrVersion("0.2"); + checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05"); + checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8"); + checkOutResourceAudit.setDesc("OK"); + checkOutResourceAudit.setComment(""); + checkOutResourceAudit.setResourceType("Resource"); + checkOutResourceAudit.setStatus("200"); + checkOutResourceAudit.setPrevVersion("0.1"); + checkOutResourceAudit.setAction("Checkout"); + // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024"); + checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN"); + checkOutResourceAudit.setResourceName("MyTestResource"); + // checkOutResourceAudit.setFields(fields); + + // Mockito.doAnswer(new Answer, + // ActionStatus> >() { + // public Either, ActionStatus> + // answer(InvocationOnMock invocation) { + // final Either, ActionStatus> either; + // final List list; + // Object[] args = invocation.getArguments(); + // Map filterMap = + // (Map) args[0]; + // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){ + // list = new + // ArrayList(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}}; + // either = Either.left(list); + // + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){ + // list = new ArrayList(); + // either = Either.left(list); + // } + // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){ + // list = new + // ArrayList(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}}; + // either = Either.left(list); + // } + // else{ + // either = null; + // } + // return either; + // } + // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap()); + // + // + List list = new ArrayList() { + { + add(createResourceAudit); + add(checkInResourceAudit); + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> result = Either.left(list); + Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result); + + List listPrev = new ArrayList(); + Either, ActionStatus> resultPrev = Either.left(listPrev); + Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev); + + List listCurr = new ArrayList() { + { + add(checkOutResourceAudit); + } + }; + Either, ActionStatus> resultCurr = Either.left(listCurr); + Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr); + + } + + private void setupBeforeDeploy(String notifyAction, String requestAction, String did) { + + DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent(); + notifyEvent.setAction(notifyAction); + notifyEvent.setDid(did); + notifyEvent.setStatus("200"); + + ResourceAdminEvent requestEvent = new ResourceAdminEvent(); + requestEvent.setAction(requestAction); + requestEvent.setDid(did); + requestEvent.setStatus("200"); + + ArrayList arrayList = new ArrayList(); + List notifyResults = arrayList; + notifyResults.add(notifyEvent); + Either, ActionStatus> eitherNotify = Either.left(notifyResults); + + Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify); + + List requestResults = new ArrayList(); + requestResults.add(requestEvent); + Either, ActionStatus> eitherRequest = Either.left(requestResults); + Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest); + + Either eitherService = Either.left(createServiceObject(true)); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService); + + List emptyList = new ArrayList(); + Either, ActionStatus> emptyEventList = Either.left(emptyList); + Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test @Ignore + public void testFindGroupInstanceOnRelatedComponentInstance() { + + Class targetClass = ServiceBusinessLogic.class; + String methodName = "findGroupInstanceOnRelatedComponentInstance"; + Object invalidId = "invalidId"; + + Component service = createNewService(); + List componentInstances = service.getComponentInstances(); + + Either, ResponseFormat> findGroupInstanceRes; + Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + Class[] argClasses = {Component.class, String.class,String.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + + findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId())); + assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId())); + + Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()}; + + findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593")); + + Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId}; + + findGroupInstanceRes = (Either, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId); + assertTrue(findGroupInstanceRes != null); + assertTrue(findGroupInstanceRes.isRight()); + assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653")); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + private Component createNewService() { + + Service service = new Service(); + int listSize = 3; + service.setName("serviceName"); + service.setUniqueId("serviceUniqueId"); + List componentInstances = new ArrayList<>(); + ComponentInstance ci; + for(int i= 0; i groupInstances= new ArrayList<>(); + GroupInstance gi; + for(int j = 0; j createResponse = bl.createService(service, user); + assertTrue(createResponse.isLeft()); + service = createResponse.left().value(); + assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName())); + assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion())); + } + + + private Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java new file mode 100644 index 0000000000..fe7152608c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java @@ -0,0 +1,202 @@ +package org.openecomp.sdc.be.components; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; +import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 10/26/2017. + */ +public class ServiceDistributionBLTest { + + @InjectMocks + ServiceBusinessLogic bl = new ServiceBusinessLogic(); + + @Mock + ServiceDistributionValidation serviceDistributionValidation; + + @Mock + HealthCheckBusinessLogic healthCheckBusinessLogic; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + ComponentsUtils componentsUtils; + + @Mock + DistributionEngine distributionEngine; + + private Service serviceToActivate; + private ActivationRequestInformation activationRequestInformation; + private String WORKLOAD_CONTEXT = "vnfContext"; + private String TENANT = "tenant"; + private String DID = "distributionId"; + private User modifier; + + + public ServiceDistributionBLTest() { + } + + @Before + public void setup() { + + ExternalConfiguration.setAppName("catalog-be"); + MockitoAnnotations.initMocks(this); + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + bl.setComponentsUtils(componentsUtils); + serviceToActivate = new Service(); + serviceToActivate.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED); + activationRequestInformation = new ActivationRequestInformation(serviceToActivate, WORKLOAD_CONTEXT, TENANT); + when(toscaOperationFacade.getToscaElement(anyString(), any(ComponentParametersView.class))) + .thenReturn(Either.left(serviceToActivate)); + when(distributionEngine.buildServiceForDistribution(any(Service.class), anyString(), anyString())) + .thenReturn(new NotificationDataImpl()); + modifier = new User(); + modifier.setUserId("uid"); + modifier.setFirstName("user"); + } + + @Test + public void testActivateServiceOnTenantValidationFails() { + int VALIDATION_FAIL_STATUS = 666; + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS))); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == VALIDATION_FAIL_STATUS); + } + + @Test + public void testNoDeploymentArtifacts() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 409); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4139")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionAuthenticationFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.AUTHENTICATION_ERROR); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionUnknownHostFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.UNKNOWN_HOST); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionConnectionErrorFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.CONNNECTION_ERROR); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml + @Test + public void testDistributionObjectNotFoundFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.OBJECT_NOT_FOUND); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionGeneralFails() { + mockAllMethodsUntilDENotification(); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString())) + .thenReturn(ActionStatus.GENERAL_ERROR); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isRight()); + assertTrue(stringResponseFormatEither.right().value().getStatus() == 502); + assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676")); + } + + @Test + public void testDistributionOk() { + mockAllMethodsUntilDENotification(); + ThreadLocalsHolder.setUuid(DID); + when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString())) + .thenReturn(ActionStatus.OK); + Either stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults(); + assertTrue(stringResponseFormatEither.isLeft()); + assertTrue(stringResponseFormatEither.left().value().equals(DID)); + } + + private void mockAllMethodsUntilDENotification() { + when(serviceDistributionValidation.validateActivateServiceRequest + (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class))) + .thenReturn(Either.left(activationRequestInformation)); + when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true); + when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class))) + .thenReturn(StorageOperationStatus.OK); + } + + private Either callActivateServiceOnTenantWIthDefaults() { + return bl.activateServiceOnTenantEnvironment("serviceId", "envId", modifier, new ServiceDistributionReqInfo("workload")); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java deleted file mode 100644 index 90a02a2fc5..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.openecomp.sdc.be.components.clean; - -import org.junit.Test; - - -public class AsdcComponentsCleanerTaskTest { - - private AsdcComponentsCleanerTask createTestSubject() { - return new AsdcComponentsCleanerTask(); - } - - - @Test - public void testInit() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.init(); - } - - - @Test - public void testDestroy() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.destroy(); - } - - - @Test - public void testStartTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.startTask(); - } - - - @Test - public void testStopTask() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.stopTask(); - } - - - - - - @Test - public void testRun() throws Exception { - AsdcComponentsCleanerTask testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.run(); - } -} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java new file mode 100644 index 0000000000..7df88c1cd9 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.apache.http.HttpStatus; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static org.junit.Assert.assertTrue; + +public class AaiMockRequestHandlerTest extends BeConfDependentTest { + + @Ignore + @Test + public void testGetOperationalEnvJson() { + String id = "OEid4"; + AaiRequestHandler aaiRequestHandler = new AaiRequestHandler(); + aaiRequestHandler.init(); + HttpResponse resp = aaiRequestHandler.getOperationalEnvById(id); + + if (resp.getStatusCode() == HttpStatus.SC_OK) { + try { + String response = resp.getResponse(); + System.out.println("The rest response is:"); + System.out.println(response); + + OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(response); + + System.out.println(String.format("Get \"%s\" operational environment. %s", id, operationalEnvInfo)); + System.out.println(operationalEnvInfo); + } + catch (Exception e) { + System.out.println(String.format("Json convert to OperationalEnvInfo failed with exception %s", e)); + System.out.println(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + else { + System.out.println("The rest response is:"); + String response = resp.getResponse(); + System.out.println(response); + System.out.println(String.format("Get \"%s\" operational environment failed with statusCode: %s, response: %s, description: %s", id, resp.getStatusCode(), resp.getResponse(), resp.getDescription())); + System.out.println(resp.getStatusCode()); + } + + assertTrue(true); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java new file mode 100644 index 0000000000..d425e6d0f5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java @@ -0,0 +1,77 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaIdentityManager; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class CambriaHandlerTest { + @Spy + private CambriaHandler handler = new CambriaHandler(); + + @Mock + private CambriaIdentityManager createIdentityManager; + + private ApiCredential apiCredential = new ApiCredential("apiKey", "apiSecret"); + + @BeforeClass + public static void beforeClass() { + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + new ConfigurationManager(configurationSource); + } + + + @Before + public void startUp() throws MalformedURLException, GeneralSecurityException { + doReturn(createIdentityManager).when(handler).buildCambriaClient(any()); + } + + @Test + public void testCreateUebKeys() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenReturn(apiCredential); + Either eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + + Mockito.verify(createIdentityManager).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isLeft()); + + } + + @Test + public void testCreateUebKeys_FAIL() throws HttpException, CambriaApiException, IOException { + Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenThrow(new CambriaApiException("Error Message")); + Either eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") ); + Mockito.verify(createIdentityManager, Mockito.never()).setApiCredentials(Mockito.anyString(), Mockito.anyString()); + assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isRight()); + CambriaErrorResponse response = eitherCreateUebKeys.right().value(); + assertEquals("Unexpected Operational Status", CambriaOperationStatus.CONNNECTION_ERROR, response.getOperationStatus()); + assertEquals("Unexpected HTTP Code", 500, response.getHttpCode().intValue()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java new file mode 100644 index 0000000000..45906c6f30 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.nsa.mr.client.MRConsumer; +import com.google.gson.GsonBuilder; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DmaapConsumerConfiguration; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.concurrent.ExecutorService; +import java.util.stream.IntStream; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context-test.xml") +public class Dev2DevDmaapConsumerTest { + @Autowired + private ExecutorFactory executorFactory; + @Autowired + private DmaapClientFactory dmaapClientFactory; + + static ExecutorService notificationExecutor; + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @Test + public void runConsumer() throws Exception{ + boolean isRunConsumer = false ; //change this to true if you wish to run consumer,default should be false + if ( isRunConsumer ){ + consumeDmaapTopic(); + }else{ + System.out.println( "CONSUMER TEST is disabled!!!! "); + } + assert true; + } + //@Ignore + //@Test + public void consumeDmaapTopic() throws Exception { + Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + System.out.println("uncaughtException -> "); + } + }; + + DmaapConsumerConfiguration dmaapConsumerParams = configurationManager.getConfiguration().getDmaapConsumerConfiguration(); + String topic = dmaapConsumerParams.getTopic(); + System.out.println(String.format( "Starting to consume topic %s for DMAAP consumer with the next parameters %s. ", topic, dmaapConsumerParams) ); + MRConsumer consumer = dmaapClientFactory.create( dmaapConsumerParams ); + notificationExecutor = executorFactory.create(topic + "Consumer", handler); + final int LIMIT = 2; + IntStream.range(0,LIMIT).forEach( i -> { + System.out.println("Trying to fetch messages from topic: "+ topic); + try { + Iterable messages = consumer.fetch(); + if (messages != null) { + for (String msg : messages) { + System.out.println(String.format( "The DMAAP message %s received. The topic is %s.", msg, topic) ); + handleMessage(msg); + } + } + } + catch (Exception e) { + System.out.println("The exception occured upon fetching DMAAP message "+ e); + } + } + ); + + + } + private void handleMessage(String msg){ + try{ + DmaapNotificationDataImpl notificationData = new GsonBuilder().create().fromJson(msg,DmaapNotificationDataImpl.class); + System.out.println( "successfully parsed notification for environemnt "+notificationData.getOperationalEnvironmentId()); + }catch (Exception e){ + System.out.println( "failed to parse notification"); + } + } + @After + public void after(){ + if (notificationExecutor!=null && !notificationExecutor.isTerminated()) + notificationExecutor.shutdown(); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java index 8d48a4c320..04aa242b03 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java @@ -20,13 +20,6 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -38,131 +31,138 @@ import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class DistributionEngineConfigTest { - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } - @Test - public void validateMissingEnvironments() { + @Test + public void validateMissingEnvironments() { - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - String uebPublicKey = "uebPublicKey"; - String uebSecretKey = "uebSecretKey"; + String uebPublicKey = "uebPublicKey"; + String uebSecretKey = "uebSecretKey"; - DistributionEngine distributionEngine = new DistributionEngine(); + DistributionEngine distributionEngine = new DistributionEngine(); - List environments = new ArrayList(); - environments.add("PROD"); - deConfiguration.setEnvironments(environments); + List environments = new ArrayList(); + environments.add("PROD"); + deConfiguration.setEnvironments(environments); - List servers = new ArrayList(); - servers.add("server1:80"); - servers.add("server2:8080"); + List servers = new ArrayList(); + servers.add("server1:80"); + servers.add("server2:8080"); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); - ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); + ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes); - ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); - deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); + ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig(); + deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes); - deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); - deConfiguration.setDistributionStatusTopicName("statusTopic"); + deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName"); + deConfiguration.setDistributionStatusTopicName("statusTopic"); - DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); - distributionStatusTopic.setConsumerGroup("asdc-group"); - distributionStatusTopic.setConsumerId("asdc-id"); - distributionStatusTopic.setFetchTimeSec(20); - distributionStatusTopic.setPollingIntervalSec(20); - deConfiguration.setDistributionStatusTopic(distributionStatusTopic); + DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig(); + distributionStatusTopic.setConsumerGroup("asdc-group"); + distributionStatusTopic.setConsumerId("asdc-id"); + distributionStatusTopic.setFetchTimeSec(20); + distributionStatusTopic.setPollingIntervalSec(20); + deConfiguration.setDistributionStatusTopic(distributionStatusTopic); - deConfiguration.setUebServers(servers); - deConfiguration.setUebPublicKey(uebPublicKey); - deConfiguration.setUebSecretKey(uebSecretKey); - deConfiguration.setInitMaxIntervalSec(8); - deConfiguration.setInitRetryIntervalSec(3); + deConfiguration.setUebServers(servers); + deConfiguration.setUebPublicKey(uebPublicKey); + deConfiguration.setUebSecretKey(uebSecretKey); + deConfiguration.setInitMaxIntervalSec(8); + deConfiguration.setInitRetryIntervalSec(3); - boolean isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + boolean isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebServers(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebServers(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebServers(servers); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebServers(servers); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setEnvironments(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setEnvironments(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setEnvironments(environments); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setEnvironments(environments); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebPublicKey(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebPublicKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebPublicKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebPublicKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setUebSecretKey(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setUebSecretKey(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setUebSecretKey(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setUebSecretKey(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setDistributionNotifTopicName(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setDistributionNotifTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionNotifTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setDistributionNotifTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setDistributionStatusTopicName(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setDistributionStatusTopicName(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setDistributionStatusTopicName(uebPublicKey); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setDistributionStatusTopicName(uebPublicKey); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setInitMaxIntervalSec(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setInitMaxIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitMaxIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setInitMaxIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - deConfiguration.setInitRetryIntervalSec(null); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertFalse("check empty configuration", isValid); + deConfiguration.setInitRetryIntervalSec(null); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertFalse("check empty configuration", isValid); - deConfiguration.setInitRetryIntervalSec(8); - isValid = distributionEngine.validateConfiguration(deConfiguration); - assertTrue("check empty configuration", isValid); + deConfiguration.setInitRetryIntervalSec(8); + isValid = distributionEngine.validateConfiguration(deConfiguration); + assertTrue("check empty configuration", isValid); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java index 990ea4f99b..1fa0fc60b7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java @@ -20,115 +20,114 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.List; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; -import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; -public class DistributionEngineHealthCheckTest extends BaseConfDependentTest { - - @Mock - private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); - - DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); - - Gson gson = new Gson(); - - Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); - - // - // @Test - // public void validateDownWhenEnvAreDown() { - // - // Map envNamePerStatus = new HashMap<>(); - // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); - // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); - // - // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); - // - // HealthCheckInfo healthCheckInfo = - // distributionEngineClusterHealth.getHealthCheckInfo(); - // assertEquals("verify down", HealthCheckStatus.DOWN, - // healthCheckInfo.getHealthCheckStatus()); - // assertEquals("verify DE component", HealthCheckComponent.DE, - // healthCheckInfo.getHealthCheckComponent()); - // - // } - - @Test - public void validateUpWhenQuerySucceed() { - - // Map envNamePerStatus = new HashMap<>(); - // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); - // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); - // - // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, - // false); - - CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); - CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); - - List uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - } - - UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - Boolean call1 = healthCheckCall1.call(); - assertTrue("check response okay", call1); - - UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - Boolean call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); - } - healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - - call1 = healthCheckCall1.call(); - assertFalse("check response okay", call1); - - healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - if (uebServers.size() >= 2) { - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); - } - healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); - healthCheckCall1.setCambriaHandler(cambriaHandler); - - call1 = healthCheckCall1.call(); - assertFalse("check response okay", call1); - - healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); - healthCheckCall2.setCambriaHandler(cambriaHandler); - - call2 = healthCheckCall2.call(); - assertTrue("check response okay", call2); - - } +public class DistributionEngineHealthCheckTest extends BeConfDependentTest { + + @Mock + private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + + DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth(); + + Gson gson = new Gson(); + + Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); + + // + // @Test + // public void validateDownWhenEnvAreDown() { + // + // Map envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(false)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus); + // + // HealthCheckInfo healthCheckInfo = + // distributionEngineClusterHealth.getHealthCheckInfo(); + // assertEquals("verify down", HealthCheckStatus.DOWN, + // healthCheckInfo.getHealthCheckStatus()); + // assertEquals("verify DE component", HealthCheckComponent.DE, + // healthCheckInfo.getHealthCheckComponent()); + // + // } + + @Test + public void validateUpWhenQuerySucceed() { + + // Map envNamePerStatus = new HashMap<>(); + // envNamePerStatus.put("PROD1", new AtomicBoolean(true)); + // envNamePerStatus.put("PROD2", new AtomicBoolean(false)); + // + // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus, + // false); + + CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500); + CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403); + + List uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers(); + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + + UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + Boolean call1 = healthCheckCall1.call(); + assertTrue("check response okay", call1); + + UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + Boolean call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + if (uebServers.size() >= 2) { + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse); + } + healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey"); + healthCheckCall1.setCambriaHandler(cambriaHandler); + + call1 = healthCheckCall1.call(); + assertFalse("check response okay", call1); + + healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey"); + healthCheckCall2.setCambriaHandler(cambriaHandler); + + call2 = healthCheckCall2.call(); + assertTrue("check response okay", call2); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java index 5bf12d56bc..03a6625cae 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java @@ -20,19 +20,9 @@ package org.openecomp.sdc.be.components.distribution.engine; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.junit.BeforeClass; +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -41,224 +31,252 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; -import fj.data.Either; - -public class DistributionEngineInitTaskTest { - - @Mock - private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - @Mock - private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); - - // public static final IAuditingDao iAuditingDao = - // Mockito.mock(AuditingDao.class); - - @BeforeClass - public static void setup() { - // ExternalConfiguration.setAppName("distribEngine1"); - ExternalConfiguration.setAppName("catalog-be"); - ExternalConfiguration.setConfigDir("src/test/resources/config"); - ExternalConfiguration.listenForChanges(); - - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); - - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } - - @Test - public void checkIncrement() { - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - - for (int i = 1; i < 5; i++) { - initTask.incrementRetryInterval(); - assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); - } - - initTask.incrementRetryInterval(); - assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); - - } - - @Test - public void testInitFlowScenarioSuccess() { - - String notifTopic = "notif"; - String statusTopic = "status"; - - List uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); - Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); - - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(cambriaErrorResponse); - - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - boolean initFlow = initTask.initFlow(); - assertTrue("check init flow succeed", initFlow); - - } - - @Test - public void testInitFlowScenarioSuccessTopicsAlreadyExists() { - - String envName = "PrOD"; - String notifTopic = "notif"; - String statusTopic = "status"; - - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; - Set topics = new HashSet(); - topics.add(realNotifTopic); - topics.add(realStatusTopic); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - List uebServers = new ArrayList<>(); - uebServers.add("server1"); - Either, CambriaErrorResponse> left = Either.left(topics); - - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); - - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(cambriaErrorResponse); - - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - try { - boolean initFlow = initTask.initFlow(); - assertTrue("check init flow succeed", initFlow); - } catch (Exception e) { - assertTrue("Should not throw exception", false); - } - - } +public class DistributionEngineInitTaskTest { - @Test - public void testInitFlowScenarioFailToRegister() { + @Mock + private ComponentsUtils componentsUtils; - String notifTopic = "notif"; - String statusTopic = "status"; - - List uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); - Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - deConfiguration.setDistributionNotifTopicName(notifTopic); - deConfiguration.setDistributionStatusTopicName(statusTopic); - CreateTopicConfig createTopic = new CreateTopicConfig(); - createTopic.setPartitionCount(1); - createTopic.setReplicationCount(1); - deConfiguration.setCreateTopic(createTopic); + @Mock + private CambriaHandler cambriaHandler; - cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + ExternalConfiguration.setConfigDir("src/test/resources/config"); + ExternalConfiguration.listenForChanges(); - String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); - String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); - when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); + new ConfigurationManager(configurationSource); - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + componentsUtils = Mockito.mock(ComponentsUtils.class); + cambriaHandler = Mockito.mock(CambriaHandler.class); + } + + @Test + public void checkIncrement() { - when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class))) - .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + + for (int i = 1; i < 5; i++) { + initTask.incrementRetryInterval(); + assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i)); + } + + initTask.incrementRetryInterval(); + assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry); + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioSuccess() { + String notifTopic = "notif"; + String statusTopic = "status"; + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); - boolean initFlow = initTask.initFlow(); - assertFalse("check init flow failed", initFlow); + } - } + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioSuccessTopicsAlreadyExists() { - @Test - public void testInitFlowScenario1GetTopicsFailed() { - - List uebServers = new ArrayList<>(); - uebServers.add("server1"); - CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); - Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); - when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); - - String envName = "PrOD"; - - DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); - deConfiguration.setUebServers(uebServers); - int retry = 2; - int maxRetry = 40; - deConfiguration.setInitRetryIntervalSec(retry); - deConfiguration.setInitMaxIntervalSec(maxRetry); - DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null); - initTask.setCambriaHandler(cambriaHandler); - - boolean initFlow = initTask.initFlow(); - assertFalse("check init flow failed", initFlow); - - } + String envName = "PrOD"; + String notifTopic = "notif"; + String statusTopic = "status"; + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + + Set topics = new HashSet(); + topics.add(realNotifTopic); + topics.add(realStatusTopic); + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + Either, CambriaErrorResponse> left = Either.left(topics); + + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left); + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cambriaErrorResponse); + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + try { + boolean initFlow = initTask.initFlow(); + assertTrue("check init flow succeed", initFlow); + } catch (Exception e) { + assertTrue("Should not throw exception", false); + } + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenarioFailToRegister() { + + String notifTopic = "notif"; + String statusTopic = "status"; + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + deConfiguration.setDistributionNotifTopicName(notifTopic); + deConfiguration.setDistributionStatusTopicName(statusTopic); + CreateTopicConfig createTopic = new CreateTopicConfig(); + createTopic.setPartitionCount(1); + createTopic.setReplicationCount(1); + deConfiguration.setCreateTopic(createTopic); + + cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK); + + String realNotifTopic = notifTopic + "-" + envName.toUpperCase(); + String realStatusTopic = statusTopic + "-" + envName.toUpperCase(); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK)); + + when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic))) + .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR)); + + + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + @SuppressWarnings("unchecked") + @Test + public void testInitFlowScenario1GetTopicsFailed() { + + List uebServers = new ArrayList<>(); + uebServers.add("server1"); + CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR); + Either, CambriaErrorResponse> right = Either.right(cambriaErrorResponse); + when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right); + + String envName = "PrOD"; + + DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration(); + deConfiguration.setUebServers(uebServers); + int retry = 2; + int maxRetry = 40; + deConfiguration.setInitRetryIntervalSec(retry); + deConfiguration.setInitMaxIntervalSec(maxRetry); + DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration)); + initTask.setCambriaHandler(cambriaHandler); + + boolean initFlow = initTask.initFlow(); + assertFalse("check init flow failed", initFlow); + + } + + private OperationalEnvironmentEntry readEnvFromConfig(DistributionEngineConfiguration distributionEngineConfiguration) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey()); + entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey()); + Set puebEndpoints = new HashSet<>(); + if(distributionEngineConfiguration.getUebServers() != null) + puebEndpoints.addAll(distributionEngineConfiguration.getUebServers()); + entry.setDmaapUebAddress(puebEndpoints); + String envName = "UNKNOWN"; + if(CollectionUtils.isNotEmpty(distributionEngineConfiguration.getEnvironments())) + envName = distributionEngineConfiguration.getEnvironments().get(0); + entry.setEnvironmentId(envName); + return entry; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java new file mode 100644 index 0000000000..b1a43eaa57 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.OperationalEnvironmentBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class DistributionEngineTest { + + public static final String DISTRIBUTION_ID = "distId"; + public static final String ENV_ID = "envId"; + public static final String USER_ID = "userId"; + public static final String MODIFIER = "modifier"; + + @InjectMocks + private DistributionEngine testInstance; + + @Mock + private EnvironmentsEngine environmentsEngine; + + @Mock + private DistributionNotificationSender distributionNotificationSender; + + private DummyDistributionConfigurationManager distributionEngineConfigurationMock; + + private Map envs; + + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + envs = getEnvs(ENV_ID); + } + + @Test + public void notifyService() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.OK, actionStatus); + } + + @Test + public void notifyService_couldNotResolveEnvironment() throws Exception { + when(environmentsEngine.getEnvironments()).thenReturn(envs); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, new Service(), new NotificationDataImpl(), "someNonExisitngEnv", USER_ID, MODIFIER); + assertEquals(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, actionStatus); + verifyZeroInteractions(distributionNotificationSender); + } + + @Test + public void notifyService_failedWhileSendingNotification() throws Exception { + NotificationDataImpl notificationData = new NotificationDataImpl(); + Service service = new Service(); + when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID)); + when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic"); + when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class), + any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER))) + .thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER); + assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); + } + + private Map getEnvs(String ... environmentIds) { + Set uebAddress = new HashSet<>(); + uebAddress.add("someAddress"); + return Stream.of(environmentIds) + .map(id -> new OperationalEnvironmentBuilder().setEnvId(id).setDmaapUebAddress(uebAddress).build()) + .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity())); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java new file mode 100644 index 0000000000..1118385143 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java @@ -0,0 +1,37 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.common.api.ConfigurationListener; +import org.openecomp.sdc.common.api.ConfigurationSource; + +public class DummyDistributionConfigurationManager { + + private DistributionEngineConfiguration configurationMock = Mockito.mock(DistributionEngineConfiguration.class); + + public DummyDistributionConfigurationManager() { + new ConfigurationManager(new DummyConfigurationSource()); + } + + public class DummyConfigurationSource implements ConfigurationSource { + + @SuppressWarnings("unchecked") + @Override + public T getAndWatchConfiguration(Class className, ConfigurationListener configurationListener) { + if (className.equals(DistributionEngineConfiguration.class)) { + return (T)configurationMock; + } + return null; + } + + @Override + public void addWatchConfiguration(Class className, ConfigurationListener configurationListener) { + + } + } + + public DistributionEngineConfiguration getConfigurationMock() { + return configurationMock; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java new file mode 100644 index 0000000000..514618c89a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java @@ -0,0 +1,190 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import fj.data.Either; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.DistributionEngineConfiguration; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.info.OperationalEnvInfo; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(value = MockitoJUnitRunner.class) +public class EnvironmentsEngineTest { + + @InjectMocks + private EnvironmentsEngine envEngine; + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ConfigurationManager configurationManager; + @Mock + private DistributionEngineConfiguration distributionEngineConfiguration; + @Mock + private AaiRequestHandler aaiRequestHandler; + + @Before + public void preStart() { + when(configurationManager.getDistributionEngineConfiguration()).thenReturn(distributionEngineConfiguration); + envEngine.setConfigurationManager(configurationManager); + } + + @Test + public void testInit() { + List entryList = Arrays.asList(createOpEnvEntry("Env1"), createOpEnvEntry("Env2")); + Either, CassandraOperationStatus> successEither = Either.left(entryList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(successEither); + + when(distributionEngineConfiguration.getEnvironments()).thenReturn(Arrays.asList("Env Loaded From Configuration")); + when(distributionEngineConfiguration.getUebPublicKey()).thenReturn("Dummy Public Key"); + when(distributionEngineConfiguration.getUebSecretKey()).thenReturn("Dummy Private Key"); + when(distributionEngineConfiguration.getUebServers()).thenReturn( + Arrays.asList("uebsb91kcdc.it.att.com:3904", "uebsb92kcdc.it.att.com:3904", "uebsb91kcdc.it.att.com:3904")); + + envEngine.init(); + + Map mapEnvs = envEngine.getEnvironments(); + assertEquals("unexpected size of map",3, mapEnvs.size()); + } + + + @Test + public void testGetFullOperationalEnvByIdSuccess() { + String json = getFullOperationalEnvJson(); + + HttpResponse restResponse = new HttpResponse(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + @Test + public void testGetPartialOperationalEnvByIdSuccess() { + String json = getPartialOperationalEnvJson(); + + HttpResponse restResponse = new HttpResponse(json, HttpStatus.SC_OK, "Successfully completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isLeft()); + + OperationalEnvInfo operationalEnvInfo = response.left().value(); + + assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json); + } + + + @Test + public void testGetOperationalEnvByIdFailedByJsonConvert() { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + + HttpResponse restResponse = new HttpResponse(jsonCorrupted, HttpStatus.SC_OK, "Successfully Completed"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_INTERNAL_SERVER_ERROR, response.right().value()); + } + + @Test + public void testGetOperationalEnvByIdFailed404() { + String json = getFullOperationalEnvJson(); + HttpResponse restResponse = new HttpResponse(json, HttpStatus.SC_NOT_FOUND, "Not Found"); + when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse); + + Either response = envEngine.getOperationalEnvById("DummyId"); + assertTrue("The operational environment request ran as not expected", response.isRight()); + assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_NOT_FOUND, response.right().value()); + } + + + @Test(expected = IOException.class) + public void testCorruptedOperationalEnvJson() throws IOException { + String jsonCorrupted = getCorruptedOperationalEnvJson(); + OperationalEnvInfo.createFromJson(jsonCorrupted); + } + + private String getCorruptedOperationalEnvJson() { + return "{\"OPERATIONAL-environment-name\":\"Op Env Name\"," + + "\"OPERATIONAL-environment-type\":\"VNF\"," + + "\"OPERATIONAL-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"}"; + } + + private String getPartialOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"UUID of Operational Environment\"," + + "\"operational-environment-name\":\"Op Env Name\"," + + "\"operational-environment-type\":\"VNF\"," + + "\"operational-environment-status\":\"Activate\"," + + "\"tenant-context\":\"Test\"," + + "\"workload-context\":\"VNF_Development\"," + + "\"resource-version\":\"1505228226913\"," + + "\"relationship-list\":{" + + "\"relationship\":[]" + + "}" + + "}"; + } + + private String getFullOperationalEnvJson() { + return "{" + + "\"operational-environment-id\":\"OEid1\"," + + "\"operational-environment-name\":\"OEname1\"," + + "\"operational-environment-type\":\"OEtype1\"," + + "\"operational-environment-status\":\"OEstatus1\"," + + "\"tenant-context\":\"OEtenantcontext1\"," + + "\"workload-context\":\"OEworkloadcontext1\"," + + "\"resource-version\":\"1511363173278\"," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-to\":\"operational-environment\"," + + "\"relationship-label\":\"managedBy\"," + + "\"related-link\":\"/aai/v12/cloud-infrastructure/operational-environments/operational-environment/OEid3\"," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"operational-environment.operational-environment-id\"," + + "\"relationship-value\":\"OEid3\"" + + "}" + + "]," + + "\"related-to-property\":[" + + "{" + + "\"property-key\":\"operational-environment.operational-environment-name\"," + + "\"property-value\":\"OEname3\"" + + "}]}]}}"; + } + + private OperationalEnvironmentEntry createOpEnvEntry(String name) { + OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry(); + entry.setEnvironmentId(name); + return entry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java new file mode 100644 index 0000000000..1a2ca4840d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java @@ -0,0 +1,310 @@ +package org.openecomp.sdc.be.components.distribution.engine; + +import com.att.aft.dme2.api.DME2Exception; +import com.att.aft.dme2.iterator.DME2EndpointIterator; +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import cucumber.api.java.Before; +import cucumber.api.java.en.Given; +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; +import fj.data.Either; +import org.apache.commons.lang.NotImplementedException; +import org.apache.commons.lang.math.NumberUtils; +import org.apache.http.HttpStatus; +import org.junit.Assert; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.http.client.api.HttpResponse; + +import static java.util.Objects.isNull; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class StepsTenantIsolation { + + // Notification Fields + private String operationalEnvironmentId = "28122015552391"; + private String operationalEnvironmentName = "Operational Environment Name"; + private String operationalEnvironmentType; + private String tenantContext ; + private String workloadContext; + private String action; + + @Mock + private DmaapConsumer dmaapConsumer; + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + @Mock + private DME2EndpointIteratorCreator epIterCreator; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private AaiRequestHandler aaiRequestHandler; + @Mock + private CambriaHandler cambriaHandler; + @InjectMocks + @Spy + private EnvironmentsEngine envEngine; + + private boolean isSuccessful; + private boolean cassandraUp; + + @Before + public void beforeScenario() { + MockitoAnnotations.initMocks(this); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)) + .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND)); + doNothing().when(envEngine).createUebTopicsForEnvironments(); + envEngine.init(); + } + + // ############################# Given - Start ############################# + @Given("^Dmaap consumer recieved notification with fields (.*)$") + public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable { + Gson gson = new GsonBuilder().create(); + IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class); + if (!isNull(notification.getOperationalEnvironmentType())) { + this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName(); + } + if( !isEmpty(notification.getOperationalEnvironmentId()) ){ + this.operationalEnvironmentId = notification.getOperationalEnvironmentId(); + } + if( !isNull(notification.getAction()) ){ + this.action = notification.getAction().getActionName(); + } + + } + + @Given("^Cassandra service status is (.*)$") + public void cassandra_service_status_is(String status) throws Throwable { + switch (status) { + case "UP": + this.cassandraUp = true; + break; + case "DOWN": + when(operationalEnvironmentDao.get(operationalEnvironmentId)) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.GENERAL_ERROR); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^Record status is (.*)$") + public void record_status_is(String status) throws Throwable { + if (!cassandraUp) { + return; + } + Either eitherResult; + final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class); + switch (status) { + case "FOUND_IN_PROGRESS": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_COMPLETED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName()); + eitherResult = Either.left(entryMock); + break; + case "FOUND_FAILED": + when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName()); + eitherResult = Either.left(entryMock); + break; + case "NOT_FOUND": + eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND); + break; + default: + throw new NotImplementedException(); + } + + when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult); + when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class))) + .thenReturn(CassandraOperationStatus.OK); + } + + @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$") + public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable { + this.tenantContext = tenant; + this.workloadContext = workload; + HttpResponse resp = Mockito.mock(HttpResponse.class); + when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp); + switch (aaiServiceStatus) { + case "UP": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK); + String aaiResponseTemplate = + //@formatter:off + "{\r\n" + + " \"operational-environment-id\": \"%s\",\r\n" + + " \"operational-environment-name\": \"%s\",\r\n" + + " \"operational-environment-type\": \"%s\",\r\n" + + " \"operational-environment-status\": \"IN-PROGRESS\",\r\n" + + " \"tenant-context\": \"%s\",\r\n" + + " \"workload-context\": \"%s\"\r\n" + + " }"; + //@formatter:on + when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId, + operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext)); + + break; + case "DOWN": + when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT); + break; + default: + throw new NotImplementedException(); + } + } + + @Given("^AFT_DME service status is (.*)$") + public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable { + switch (aftDmeStatus) { + case "UP": + DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class); + when(mockItr.hasNext()).thenReturn(false); + when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr); + break; + case "DOWN": + when(epIterCreator.create(Mockito.anyString())) + .thenThrow(new DME2Exception("dummyCode", new NotImplementedException())); + break; + default: + throw new NotImplementedException(); + } + } + + @SuppressWarnings("unchecked") + @Given("^UEB service status is (.*)$") + public void ueb_service_status_is(String status) throws Throwable { + + Either response; + switch (status) { + case "UP": + ApiCredential apiCredential = Mockito.mock(ApiCredential.class); + when(apiCredential.getApiKey()).thenReturn("MockAPIKey"); + when(apiCredential.getApiSecret()).thenReturn("MockSecretKey"); + response = Either.left(apiCredential); + break; + case "DOWN": + CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class); + response = Either.right(cambriaError); + break; + default: + throw new NotImplementedException(); + } + when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response); + } + // ############################# Given - End ############################# + + // ############################# When - Start ############################# + + @When("^handle message is activated$") + public void handle_message_is_activated() throws Throwable { + this.isSuccessful = envEngine.handleMessage(buildNotification()); + } + // ############################# When - End ############################# + + // ############################# Then - Start ############################# + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of eventType (.*)$") + public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class), + Mockito.any(IDmaapAuditNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to write message to audit log and table (.*)$") + public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable { + int count = isUnsupportedTypeEventRecorded ? 2 : 1; + verify(componentsUtils, Mockito.atLeast(count)) + .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId), + Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of action (.*)$") + public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^handle message activates validation of state (.*)$") + public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated))) + .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to save in-progress record (.*)$") + public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to get environment info from A&AI API (.*)$") + public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @SuppressWarnings("unchecked") + @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$") + public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts( + Mockito.anyString(), Mockito.anyString()); + + } + + @SuppressWarnings("unchecked") + @Then("^trying to create Ueb keys (.*)$") + public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^trying to create Ueb Topics (.*)$") + public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable { + verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))) + .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + } + + @Then("^handle message finished successfully (.*)$") + public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable { + Assert.assertTrue(this.isSuccessful == isSuccessfull); + } + + // ############################# Then - End ############################# + + private String buildNotification() { + String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n" + + " \"operationalEnvironmentName\": \"%s\",\r\n" + + " \"operationalEnvironmentType\": \"%s\",\r\n" + " \"tenantContext\": \"%s\",\r\n" + + " \"workloadContext\": \"%s\",\r\n" + " \"action\": \"%s\"}"; + + String notification = String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + return notification; + } + + private int getNumberOfCallsToValidate(boolean isValidated) { + return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java deleted file mode 100644 index 712e16d97a..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.openecomp.sdc.be.components.distribution.engine; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses( - -{ DistributionEngineInitTaskTest.class, DistributionEngineConfigTest.class, DistributionEngineHealthCheckTest.class, - VfModuleArtifactPayloadTest.class }) -public class TestSuite { // nothing -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java new file mode 100644 index 0000000000..9d0e8cd683 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java @@ -0,0 +1,135 @@ +package org.openecomp.sdc.be.components.distribution.engine.rest; + +import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.matching.AnythingPattern; +import com.github.tomakehurst.wiremock.matching.UrlPattern; +import fj.data.Either; +import org.apache.http.HttpHeaders; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum; +import org.openecomp.sdc.be.components.distribution.engine.DummyDistributionConfigurationManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.http.config.*; +import org.openecomp.sdc.security.SecurityUtil; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +public class MsoRestClientTest { + + private static final String MSO_HOST = "127.0.0.1"; + private static final String MSO_API_URL = "onap/mso/infra/modelDistributions/v1"; + private static final String DISTRIBUTION_ID = "1000"; + + private MSORestClient msoRestClient; + + @ClassRule + public static WireMockRule msoRestServer = new WireMockRule(options() + .dynamicPort() + .bindAddress(MSO_HOST)); + + @Before + public void setupMsoServer() throws Exception { + String encodedPw = ""; + Either passkey = SecurityUtil.INSTANCE.decrypt(getPwd()); + if(passkey.isLeft()) { + encodedPw = passkey.left().value(); + } + else { + throw new IllegalArgumentException(passkey.right().value()); + } + + msoRestServer.resetToDefaultMappings(); + msoRestServer.stubFor(patch(urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl()))) + .withBasicAuth(getUserName(), encodedPw) + .withHeader(HttpHeaders.CONTENT_TYPE, containing("application/json")) + .withRequestBody(matchingJsonPath("$.status")) + .withRequestBody(matchingJsonPath("$.errorReason", new AnythingPattern()))//error reason is not mandatory + .willReturn(aResponse().withStatus(200))); + } + + @Before + public void setUp() throws Exception { + DummyDistributionConfigurationManager distributionEngineConfigurationMock = new DummyDistributionConfigurationManager(); + when(distributionEngineConfigurationMock.getConfigurationMock().getMsoConfig()).thenReturn(new MsoDummyConfig(msoRestServer.port())); + msoRestClient = new MSORestClient(); + } + + @Test + public void notifyDistributionComplete_emptyErrReason() throws Exception { + HttpResponse response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, ""); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + private int getNumOfRetries() { + return ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getNumOfRetries(); + } + + @Test + public void notifyDistributionComplete_noErrReason() throws Exception { + HttpResponse response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, null); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void notifyDistributionComplete_completeWithError() throws Exception { + HttpResponse response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + assertThat(response.getStatusCode()).isEqualTo(200); + } + + @Test + public void testRetries() throws Exception { + int readTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getTimeouts().getReadTimeoutMs(); + int expectedNumOfRetries = getNumOfRetries(); + + UrlPattern msoReqUrlPattern = urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl())); + msoRestServer.stubFor(patch(msoReqUrlPattern) + .willReturn(new ResponseDefinitionBuilder().withFixedDelay(readTimeout + 1))); + HttpResponse response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason"); + verify(expectedNumOfRetries + 1, patchRequestedFor(msoReqUrlPattern)); + assertThat(response.getStatusCode()).isEqualTo(500); + } + + private static String getDistributionsUrl() { + return "/distributions"; + } + + private static String getUserName() { + return "asdc"; + } + + private static String getPwd() { + return "OTLEp5lfVhYdyw5EAtTUBQ=="; + } + + private static class MsoDummyConfig extends ExternalServiceConfig { + int port; + + MsoDummyConfig(int port) { + this.port = port; + + BasicAuthorization basicAuthorization = new BasicAuthorization(); + basicAuthorization.setUserName(MsoRestClientTest.getUserName()); + basicAuthorization.setPassword(getPwd()); + HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(500, 2000), basicAuthorization); + httpClientConfig.setNumOfRetries(getNumOfRetries()); + super.setHttpClientConfig(httpClientConfig); + + HttpRequestConfig httpRequestConfig = new HttpRequestConfig(); + httpRequestConfig.setServerRootUrl(String.format("http://%s:%s/%s", MSO_HOST, this.port, MSO_API_URL)); + httpRequestConfig.getResourceNamespaces().put(MSORestClient.DISTRIBUTIONS_RESOURCE_CONFIG_PARAM, getDistributionsUrl()); + super.setHttpRequestConfig(httpRequestConfig); + } + + int getNumOfRetries() { + return 1; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index c57f2a65af..bebe29f13e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -20,28 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; -import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig.Feature; -import org.codehaus.jackson.map.annotate.JsonSerialize; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -55,6 +41,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -70,6 +57,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -84,294 +72,359 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME; +import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME; public class ArtifactBusinessLogicTest { - public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - @InjectMocks - private static ArtifactsBusinessLogic artifactBL; - @Mock - private ArtifactOperation artifactOperation; - @Mock - public ComponentsUtils componentsUtils; - @Mock - private IInterfaceLifecycleOperation lifecycleOperation; - @Mock - private IUserAdminOperation userOperation; - @Mock - private IElementOperation elementOperation; - @Mock - private ArtifactCassandraDao artifactCassandraDao; - @Mock - public ToscaOperationFacade toscaOperationFacade; - @Mock - private UserBusinessLogic userBusinessLogic; - @Mock - private NodeTemplateOperation nodeTemplateOperation; - @Mock - private ArtifactsOperations artifactsOperations; - - // public static final InformationDeployedArtifactsBusinessLogic - // informationDeployedArtifactsBusinessLogic = - // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); - - public static final Resource resource = Mockito.mock(Resource.class); - private Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - - private static List getAllTypes() { - List artifactTypes = new ArrayList(); - List artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); - for (String artifactType : artifactTypesList) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return artifactTypes; - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - Either NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); - - Either, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); - - Either, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); - when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); - - Either getUserResult = Either.left(USER); - - when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); - - Either, ActionStatus> getType = Either.left(getAllTypes()); - when(elementOperation.getAllArtifactTypes()).thenReturn(getType); - - when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); - } - - @Test - public void testValidJson() { - ArtifactDefinition ad = createArtifactDef(); - - String jsonArtifact = ""; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false); - mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); - - try { - jsonArtifact = mapper.writeValueAsString(ad); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); - assertEquals(ad, afterConvert); - } - - private ArtifactDefinition createArtifactDef() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1.yaml"); - ad.setArtifactLabel("label1"); - ad.setDescription("description"); - ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - return ad; - } - - @Test - public void testInvalidStringGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidNumberGroupType() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidGroupTypeWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - ad.setTimeout(15); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testInvalidTimeoutWithSpace() { - ArtifactDefinition ad = new ArtifactDefinition(); - ad.setArtifactName("artifact1"); - ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - ad.setCreationDate(System.currentTimeMillis()); - ad.setMandatory(false); - - JsonElement jsonArtifact = gson.toJsonTree(ad); - jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); - - ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); - assertNull(afterConvert); - } - - @Test - public void testValidMibAritactsConfiguration() { - Map componentDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - Map componentInstanceDeploymentArtifacts = - ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); - assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); - } - - @Test - public void testDownloadServiceArtifactByNames() { - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); - esArtifactData.setDataAsArray(payload); - Either artifactfromESres = Either.left(esArtifactData); - when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); - List serviceList = new ArrayList<>(); - serviceList.add(service); - Either, StorageOperationStatus> getServiceRes = Either.left(serviceList); - when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); - Either downloadServiceArtifactByNamesRes = - artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); - assertTrue(downloadServiceArtifactByNamesRes.isLeft()); - assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); - } - - @Test - public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) - .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) - .build(); - - Resource component = new Resource(); - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - Either heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); - assertTrue(heatEnvPlaceHolder.isLeft()); - assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); - } - - @Test - public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { - HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); - HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); - HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); - ArtifactDefinition heatArtifact = new ArtifactBuilder() - .addHeatParam(heatParam1) - .addHeatParam(heatParam2) - .addHeatParam(heatParam3) - .build(); - - Resource component = new Resource(); - - when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); - when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) - .thenReturn(Either.left(new ArtifactDefinition())); - - Either heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); - - assertTrue(heatEnvPlaceHolder.isLeft()); - ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); - List listHeatParameters = heatEnvArtifact.getListHeatParameters(); - assertEquals(listHeatParameters.size(), 3); - verifyHeatParam(listHeatParameters.get(0), heatParam1); - verifyHeatParam(listHeatParameters.get(1), heatParam2); - verifyHeatParam(listHeatParameters.get(2), heatParam3); - } - - private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { - assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); - assertNull(heatEnvParam.getCurrentValue()); - } + public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis()); + private final static String RESOURCE_INSTANCE_NAME = "Service-111"; + private final static String INSTANCE_ID = "S-123-444-ghghghg"; + + private final static String ARTIFACT_NAME = "service-Myservice-template.yml"; + private final static String ARTIFACT_LABEL = "assettoscatemplate"; + private final static String ES_ARTIFACT_ID = "123123dfgdfgd0"; + private final static byte[] PAYLOAD = "some payload".getBytes(); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + @InjectMocks + private static ArtifactsBusinessLogic artifactBL; + @Mock + private ArtifactOperation artifactOperation; + @Mock + public ComponentsUtils componentsUtils; + @Mock + private IInterfaceLifecycleOperation lifecycleOperation; + @Mock + private IUserAdminOperation userOperation; + @Mock + private IElementOperation elementOperation; + @Mock + private ArtifactCassandraDao artifactCassandraDao; + @Mock + public ToscaOperationFacade toscaOperationFacade; + @Mock + private UserBusinessLogic userBusinessLogic; + @Mock + private NodeTemplateOperation nodeTemplateOperation; + @Mock + private ArtifactsOperations artifactsOperations; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + TitanDao titanDao; + + // public static final InformationDeployedArtifactsBusinessLogic + // informationDeployedArtifactsBusinessLogic = + // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); + + public static final Resource resource = Mockito.mock(Resource.class); + private Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + + private static List getAllTypes() { + List artifactTypes = new ArrayList(); + List artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return artifactTypes; + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + Either NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND); + + Either, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2); + + Either, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND); + when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces); + + Either getUserResult = Either.left(USER); + + when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult); + + Either, ActionStatus> getType = Either.left(getAllTypes()); + when(elementOperation.getAllArtifactTypes()).thenReturn(getType); + + when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC); + } + + @Test + public void testValidJson() { + ArtifactDefinition ad = createArtifactDef(); + + String jsonArtifact = ""; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try { + jsonArtifact = mapper.writeValueAsString(ad); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class); + assertEquals(ad, afterConvert); + } + + private ArtifactDefinition createArtifactDef() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1.yaml"); + ad.setArtifactLabel("label1"); + ad.setDescription("description"); + ad.setArtifactType(ArtifactTypeEnum.HEAT.getType()); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + return ad; + } + + @Test + public void testInvalidStringGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidNumberGroupType() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidGroupTypeWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + ad.setTimeout(15); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testInvalidTimeoutWithSpace() { + ArtifactDefinition ad = new ArtifactDefinition(); + ad.setArtifactName("artifact1"); + ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + ad.setCreationDate(System.currentTimeMillis()); + ad.setMandatory(false); + + JsonElement jsonArtifact = gson.toJsonTree(ad); + jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15"); + + ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class); + assertNull(afterConvert); + } + + @Test + public void testValidMibAritactsConfiguration() { + Map componentDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map componentInstanceDeploymentArtifacts = + ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType())); + assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType())); + } + + @Test + public void testDownloadServiceArtifactByNames() { + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); + + ESArtifactData esArtifactData =new ESArtifactData(esArtifactId); + esArtifactData.setDataAsArray(payload); + Either artifactfromESres = Either.left(esArtifactData); + when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres); + List serviceList = new ArrayList<>(); + serviceList.add(service); + Either, StorageOperationStatus> getServiceRes = Either.left(serviceList); + when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes); + Either downloadServiceArtifactByNamesRes = + artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName); + assertTrue(downloadServiceArtifactByNamesRes.isLeft()); + assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length); + } + + @Test + public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception { + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1")) + .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2")) + .build(); + + Resource component = new Resource(); + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + Either heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap()); + assertTrue(heatEnvPlaceHolder.isLeft()); + assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters()); + } + + @Test + public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception { + HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1"); + HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2"); + HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3"); + ArtifactDefinition heatArtifact = new ArtifactBuilder() + .addHeatParam(heatParam1) + .addHeatParam(heatParam2) + .addHeatParam(heatParam3) + .build(); + + Resource component = new Resource(); + + when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER)); + when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId"))) + .thenReturn(Either.left(new ArtifactDefinition())); + + Either heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap()); + + assertTrue(heatEnvPlaceHolder.isLeft()); + ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value(); + List listHeatParameters = heatEnvArtifact.getListHeatParameters(); + assertEquals(listHeatParameters.size(), 3); + verifyHeatParam(listHeatParameters.get(0), heatParam1); + verifyHeatParam(listHeatParameters.get(1), heatParam2); + verifyHeatParam(listHeatParameters.get(2), heatParam3); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, true); + } + + @Test + public void buildArtifactPayloadWhenShouldLockAndNotInTransaction() { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactName(ARTIFACT_NAME); + artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + artifactDefinition.setArtifactLabel(ARTIFACT_LABEL); + artifactDefinition.setEsId(ES_ARTIFACT_ID); + artifactDefinition.setPayload(PAYLOAD); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class) + , any(String.class))).thenReturn(Either.left(artifactDefinition)); + when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK); + when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat()); + artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME, + USER, INSTANCE_ID, true, false); + verify(titanDao, times(1)).commit(); + } + + private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) { + assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue()); + assertNull(heatEnvParam.getCurrentValue()); + } // @Test - // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ - // ArtifactDefinition createArtifactDef = createArtifactDef(); - // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); - // - // Either validateResult = artifactBL - // - // assertTrue(validateResult.isLeft()); - // ArtifactDefinition validatedArtifact = validateResult.left().value(); - // - // assertEquals(createArtifactDef.getArtifactGroupType(), - // validatedArtifact.getArtifactGroupType()); - // assertEquals(new Integer(0), validatedArtifact.getTimeout()); - // assertFalse(validatedArtifact.getMandatory()); - // assertFalse(validatedArtifact.getServiceApi()); - // - // } + // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){ + // ArtifactDefinition createArtifactDef = createArtifactDef(); + // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType()); + // + // Either validateResult = artifactBL + // + // assertTrue(validateResult.isLeft()); + // ArtifactDefinition validatedArtifact = validateResult.left().value(); + // + // assertEquals(createArtifactDef.getArtifactGroupType(), + // validatedArtifact.getArtifactGroupType()); + // assertEquals(new Integer(0), validatedArtifact.getTimeout()); + // assertFalse(validatedArtifact.getMandatory()); + // assertFalse(validatedArtifact.getServiceApi()); + // + // } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java index 8ad9bf80b2..18af7a035a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.Collections; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; @@ -34,12 +28,21 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + public class ArtifactResolverTest { private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); - private Service service, noArtifactsService; - private Resource resource, noArtifactsResource; - private ComponentInstance componentInstance, noArtifactsInstance; + private Service service; + private Service noArtifactsService; + private Resource resource; + private Resource noArtifactsResource; + private ComponentInstance componentInstance; + private ComponentInstance noArtifactsInstance; @Before public void setUp() throws Exception { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java index 41835a6cdc..9b2fb3773b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java @@ -20,17 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -46,58 +36,68 @@ import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation; import org.openecomp.sdc.common.util.CapabilityTypeNameEnum; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class CapabilityTypeImportManagerTest { - @InjectMocks - private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + @InjectMocks + private CapabilityTypeImportManager manager = new CapabilityTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() { - when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either ans = Either.left((CapabilityTypeDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() { + when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either ans = Either.left((CapabilityTypeDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void testCreateCapabilityTypes() throws IOException { - String ymlContent = getCapabilityTypesYml(); - Either, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void testCreateCapabilityTypes() throws IOException { + String ymlContent = getCapabilityTypesYml(); + Either, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - List capabilityTypesList = createCapabilityTypes.left().value(); - assertTrue(capabilityTypesList.size() == 14); - Map capibilityTypeMap = new HashMap<>(); - for (CapabilityTypeDefinition capType : capabilityTypesList) { - capibilityTypeMap.put(capType.getType(), capType); - } - assertTrue(capabilityTypesList.size() == 14); + List capabilityTypesList = createCapabilityTypes.left().value(); + assertTrue(capabilityTypesList.size() == 14); + Map capibilityTypeMap = new HashMap<>(); + for (CapabilityTypeDefinition capType : capabilityTypesList) { + capibilityTypeMap.put(capType.getType(), capType); + } + assertTrue(capabilityTypesList.size() == 14); - for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { - assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); - } + for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) { + assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName())); + } - } + } - private String getCapabilityTypesYml() throws IOException { - Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getCapabilityTypesYml() throws IOException { + Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java index 2c83c60fc6..8a07e26161 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -45,64 +36,66 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; - -import fj.data.Either; - -public class CategoriesImportManagerTest { - @InjectMocks - static CategoriesImportManager importManager = new CategoriesImportManager(); - public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - - static Logger log = Mockito.spy(Logger.class); - private static SubCategoryDefinition subcategory; - - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId("123"); - - when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer>) invocation -> { - Object[] args = invocation.getArguments(); - CategoryDefinition category = (CategoryDefinition) args[0]; - category.setUniqueId("123"); - Either ans = Either.left(category); - return ans; - }); - when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); - Either ans = Either.left(subcategory); - return ans; - } - - }); - - // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void importCategoriesTest() throws IOException { - String ymlContent = getYmlContent(); - Either>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; - } +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } +public class CategoriesImportManagerTest { + @InjectMocks + static CategoriesImportManager importManager = new CategoriesImportManager(); + public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + private static SubCategoryDefinition subcategory; + + @BeforeClass + public static void beforeClass() throws IOException { + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId("123"); + + when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer>) invocation -> { + Object[] args = invocation.getArguments(); + CategoryDefinition category = (CategoryDefinition) args[0]; + category.setUniqueId("123"); + Either ans = Either.left(category); + return ans; + }); + when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + // subcategory.setName(((SubCategoryDefinition)args[0]).getName()); + Either ans = Either.left(subcategory); + return ans; + } + + }); + + // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123"); + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void importCategoriesTest() throws IOException { + String ymlContent = getYmlContent(); + Either>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); + + } + + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 65f7ac46b6..a5d05eff2c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -1,23 +1,22 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiPredicate; - +import fj.data.Either; import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; @@ -32,214 +31,354 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiPredicate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceBusinessLogic class */ public class ComponentInstanceBusinessLogicTest { - - private final static String USER_ID = "jh0003"; - private final static String COMPONENT_ID = "componentId"; - private final static String TO_INSTANCE_ID = "toInstanceId"; - private final static String FROM_INSTANCE_ID = "fromInstanceId"; - private final static String RELATION_ID = "relationId"; - private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; - private final static String CAPABILITY_UID = "capabilityUid"; - private final static String CAPABILITY_NAME = "capabilityName"; - private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; - private final static String REQUIREMENT_UID = "requirementUid"; - private final static String REQUIREMENT_NAME = "requirementName"; - private final static String RELATIONSHIP_TYPE = "relationshipType"; - - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - private static ToscaOperationFacade toscaOperationFacade; - private static UserBusinessLogic userAdmin; - - private static ComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentInstanceBusinessLogic resourceBusinessLogic; - private static User user; - private static Component service; - private static Component resource; - private static ComponentInstance toInstance; - private static ComponentInstance fromInstance; - private static CapabilityDataDefinition capability; - private static RequirementDataDefinition requirement; - private static RequirementCapabilityRelDef relation; - - @BeforeClass - public static void setup() { - createMocks(); - setMocks(); - stubMethods(); - createComponents(); - } - - @Test - public void testGetRelationByIdSuccess(){ - getServiceRelationByIdSuccess(service); - getServiceRelationByIdSuccess(resource); - } - - @Test - public void testGetRelationByIdUserValidationFailure(){ - getServiceRelationByIdUserValidationFailure(service); - getServiceRelationByIdUserValidationFailure(resource); - } - - @Test - public void testGetRelationByIdComponentNotFoundFailure(){ - getRelationByIdComponentNotFoundFailure(service); - getRelationByIdComponentNotFoundFailure(resource); - } - - @SuppressWarnings("unchecked") - private void getServiceRelationByIdSuccess(Component component){ - Either eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either getComponentRes = Either.left(component); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either getfulfilledRequirementRes = Either.left(requirement); - when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); - - Either getfulfilledCapabilityRes = Either.left(capability); - when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); - - Either response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isLeft()); - } - - private void getServiceRelationByIdUserValidationFailure(Component component){ - Either eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - - Either response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private void getRelationByIdComponentNotFoundFailure(Component component){ - Either eitherCreator = Either.left(user); - when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); - Either getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); - - Either response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); - assertTrue(response.isRight()); - } - - private static void createMocks() { - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - userAdmin = Mockito.mock(UserBusinessLogic.class); - user = Mockito.mock(User.class); - } - - private static void setMocks() { - serviceBusinessLogic = new ServiceComponentInstanceBusinessLogic(); - serviceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - serviceBusinessLogic.setUserAdmin(userAdmin); - serviceBusinessLogic.setComponentsUtils(componentsUtils); - - resourceBusinessLogic = new VFComponentInstanceBusinessLogic(); - resourceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); - resourceBusinessLogic.setUserAdmin(userAdmin); - resourceBusinessLogic.setComponentsUtils(componentsUtils); - } - - private static void stubMethods() { - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); - } - - private static void createComponents() { - createRelation(); - createInstances(); - createService(); - createResource(); - } - - private static void createResource() { - resource = new Resource(); - resource.setUniqueId(COMPONENT_ID); - resource.setComponentInstancesRelations(Lists.newArrayList(relation)); - resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - resource.setCapabilities(toInstance.getCapabilities()); - resource.setRequirements(fromInstance.getRequirements()); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - } - - - private static void createService() { - service = new Service(); - service.setUniqueId(COMPONENT_ID); - service.setComponentInstancesRelations(Lists.newArrayList(relation)); - service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); - service.setCapabilities(toInstance.getCapabilities()); - service.setRequirements(fromInstance.getRequirements()); - service.setComponentType(ComponentTypeEnum.SERVICE); - } - - - private static void createInstances() { - toInstance = new ComponentInstance(); - toInstance.setUniqueId(TO_INSTANCE_ID); - - fromInstance = new ComponentInstance(); - fromInstance.setUniqueId(FROM_INSTANCE_ID); - - capability = new CapabilityDataDefinition(); - capability.setOwnerId(CAPABILITY_OWNER_ID); - capability.setUniqueId(CAPABILITY_UID); - capability.setName(CAPABILITY_NAME); - - Map> capabilities = new HashMap<>(); - capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); - - requirement = new RequirementDataDefinition(); - requirement.setOwnerId(REQUIREMENT_OWNER_ID); - requirement.setUniqueId(REQUIREMENT_UID); - requirement.setName(REQUIREMENT_NAME); - requirement.setRelationship(RELATIONSHIP_TYPE); - - - Map> requirements = new HashMap<>(); - requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); - - toInstance.setCapabilities(capabilities); - fromInstance.setRequirements(requirements); - } - - - private static void createRelation() { - - relation = new RequirementCapabilityRelDef(); - CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); - RelationshipInfo relationInfo = new RelationshipInfo(); - relationInfo.setId(RELATION_ID); - relationship.setRelation(relationInfo); - - relation.setRelationships(Lists.newArrayList(relationship)); - relation.setToNode(TO_INSTANCE_ID); - relation.setFromNode(FROM_INSTANCE_ID); - - relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); - relationInfo.setCapabilityUid(CAPABILITY_UID); - relationInfo.setCapability(CAPABILITY_NAME); - relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); - relationInfo.setRequirementUid(REQUIREMENT_UID); - relationInfo.setRequirement(REQUIREMENT_NAME); - RelationshipImpl relationshipImpl = new RelationshipImpl(); - relationshipImpl.setType(RELATIONSHIP_TYPE); - relationInfo.setRelationships(relationshipImpl); - } + + private final static String USER_ID = "jh0003"; + private final static String COMPONENT_ID = "componentId"; + private final static String TO_INSTANCE_ID = "toInstanceId"; + private final static String FROM_INSTANCE_ID = "fromInstanceId"; + private final static String RELATION_ID = "relationId"; + private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId"; + private final static String CAPABILITY_UID = "capabilityUid"; + private final static String CAPABILITY_NAME = "capabilityName"; + private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId"; + private final static String REQUIREMENT_UID = "requirementUid"; + private final static String REQUIREMENT_NAME = "requirementName"; + private final static String RELATIONSHIP_TYPE = "relationshipType"; + + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + private static ToscaOperationFacade toscaOperationFacade; + private static UserBusinessLogic userAdmin; + + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ForwardingPathOperation forwardingPathOperation; + private static User user; + private static UserValidations userValidations; + private static Component service; + private static Component resource; + private static ComponentInstance toInstance; + private static ComponentInstance fromInstance; + private static CapabilityDataDefinition capability; + private static RequirementDataDefinition requirement; + private static RequirementCapabilityRelDef relation; + + @BeforeClass + public static void setup() { + createMocks(); + setMocks(); + stubMethods(); + createComponents(); + + } + + @Before + public void init(){ + MockitoAnnotations.initMocks(this); + } + @Test + public void testGetRelationByIdSuccess(){ + getServiceRelationByIdSuccess(service); + getServiceRelationByIdSuccess(resource); + } + + @Test + public void testGetRelationByIdUserValidationFailure(){ + getServiceRelationByIdUserValidationFailure(service); + getServiceRelationByIdUserValidationFailure(resource); + } + + @Test + public void testGetRelationByIdComponentNotFoundFailure(){ + getRelationByIdComponentNotFoundFailure(service); + getRelationByIdComponentNotFoundFailure(resource); + } + + + + + @Test + public void testForwardingPathOnVersionChange(){ + getforwardingPathOnVersionChange(); + } + + private void getforwardingPathOnVersionChange(){ + String containerComponentParam="services"; + String containerComponentID="121-cont"; + String componentInstanceID="121-cont-1-comp"; + Service component=new Service(); + Map forwardingPaths = generateForwardingPath(componentInstanceID); + + //Add existing componentInstance to component + List componentInstanceList=new ArrayList<>(); + ComponentInstance oldComponentInstance=new ComponentInstance(); + oldComponentInstance.setName("OLD_COMP_INSTANCE"); + oldComponentInstance.setUniqueId(componentInstanceID); + oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,"1-comp"); + componentInstanceList.add(oldComponentInstance); + component.setComponentInstances(componentInstanceList); + component.setForwardingPaths(forwardingPaths); + + List componentInstanceListNew=new ArrayList<>(); + ComponentInstance newComponentInstance=new ComponentInstance(); + String new_Comp_UID="2-comp"; + newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,new_Comp_UID); + newComponentInstance.setUniqueId(new_Comp_UID); + componentInstanceListNew.add(newComponentInstance); + Component component2=new Service(); + component2.setComponentInstances(componentInstanceListNew); + + //Mock for getting component + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE)); + //Mock for getting component for componentInstance + when(toscaOperationFacade.getToscaFullElement(eq("1-comp"))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaFullElement(eq(new_Comp_UID))).thenReturn(Either.left(component2)); + + Either, ResponseFormat> resultOp = componentInstanceBusinessLogic.forwardingPathOnVersionChange + (containerComponentParam,containerComponentID,componentInstanceID,newComponentInstance); + Assert.assertEquals(1,resultOp.left().value().size()); + Assert.assertEquals("FP-ID-1",resultOp.left().value().iterator().next()); + + } + + + @Test + public void testDeleteForwardingPathsWhenComponentinstanceDeleted(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.left(new ComponentInstance())); + Assert.assertTrue(responseFormatEither.isLeft()); + + } + + @Test + public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete(){ + + ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services"); + String containerComponentID = "Service-comp"; + String componentInstanceID = "NodeA1"; + Service component = new Service(); + + component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1")); + component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2")); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component)); + when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component)); + when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>())); + Either responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance( + containerComponentID, componentInstanceID, containerComponentType, Either.right(new ResponseFormat())); + Assert.assertTrue(responseFormatEither.isRight()); + + } + + + private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode , String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol("protocol"); + forwardingPath.setDestinationPortNumber("port"); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(fromNode, toNode, + "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } + + + + private Map generateForwardingPath(String componentInstanceID) { + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName"); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + forwardingPath.setUniqueId("FP-ID-1"); + ListDataDefinition forwardingPathElementListDataDefinition = + new ListDataDefinition<>(); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY", + "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map forwardingPaths = new HashMap<>(); + forwardingPaths.put("1122", forwardingPath); + return forwardingPaths; + } + + @SuppressWarnings("unchecked") + private void getServiceRelationByIdSuccess(Component component){ + Either eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either getComponentRes = Either.left(component); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either getfulfilledRequirementRes = Either.left(requirement); + when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes); + + Either getfulfilledCapabilityRes = Either.left(capability); + when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes); + + Either response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isLeft()); + } + + private void getServiceRelationByIdUserValidationFailure(Component component){ + //Either eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND); + //when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.right(new ResponseFormat(404))); + Either response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private void getRelationByIdComponentNotFoundFailure(Component component){ + Either eitherCreator = Either.left(user); + when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator); + Either getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes); + + Either response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); + assertTrue(response.isRight()); + } + + private static void createMocks() { + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + userAdmin = Mockito.mock(UserBusinessLogic.class); + user = Mockito.mock(User.class); + userValidations = Mockito.mock(UserValidations.class); + forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class); + } + + private static void setMocks() { + componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic(); + componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade); + componentInstanceBusinessLogic.setUserAdmin(userAdmin); + componentInstanceBusinessLogic.setComponentsUtils(componentsUtils); + componentInstanceBusinessLogic.setUserValidations(userValidations); + componentInstanceBusinessLogic.setForwardingPathOperation(forwardingPathOperation); + } + + private static void stubMethods() { + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.left(user)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat); + } + + private static void createComponents() { + createRelation(); + createInstances(); + createService(); + createResource(); + } + + private static void createResource() { + resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setComponentInstancesRelations(Lists.newArrayList(relation)); + resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + resource.setCapabilities(toInstance.getCapabilities()); + resource.setRequirements(fromInstance.getRequirements()); + resource.setComponentType(ComponentTypeEnum.RESOURCE); + } + + + private static void createService() { + service = new Service(); + service.setUniqueId(COMPONENT_ID); + service.setComponentInstancesRelations(Lists.newArrayList(relation)); + service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance)); + service.setCapabilities(toInstance.getCapabilities()); + service.setRequirements(fromInstance.getRequirements()); + service.setComponentType(ComponentTypeEnum.SERVICE); + } + + + private static void createInstances() { + toInstance = new ComponentInstance(); + toInstance.setUniqueId(TO_INSTANCE_ID); + + fromInstance = new ComponentInstance(); + fromInstance.setUniqueId(FROM_INSTANCE_ID); + + capability = new CapabilityDataDefinition(); + capability.setOwnerId(CAPABILITY_OWNER_ID); + capability.setUniqueId(CAPABILITY_UID); + capability.setName(CAPABILITY_NAME); + + Map> capabilities = new HashMap<>(); + capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability))); + + requirement = new RequirementDataDefinition(); + requirement.setOwnerId(REQUIREMENT_OWNER_ID); + requirement.setUniqueId(REQUIREMENT_UID); + requirement.setName(REQUIREMENT_NAME); + requirement.setRelationship(RELATIONSHIP_TYPE); + + + Map> requirements = new HashMap<>(); + requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement))); + + toInstance.setCapabilities(capabilities); + fromInstance.setRequirements(requirements); + } + + + private static void createRelation() { + + relation = new RequirementCapabilityRelDef(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + RelationshipInfo relationInfo = new RelationshipInfo(); + relationInfo.setId(RELATION_ID); + relationship.setRelation(relationInfo); + + relation.setRelationships(Lists.newArrayList(relationship)); + relation.setToNode(TO_INSTANCE_ID); + relation.setFromNode(FROM_INSTANCE_ID); + + relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID); + relationInfo.setCapabilityUid(CAPABILITY_UID); + relationInfo.setCapability(CAPABILITY_NAME); + relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID); + relationInfo.setRequirementUid(REQUIREMENT_UID); + relationInfo.setRequirement(REQUIREMENT_NAME); + RelationshipImpl relationshipImpl = new RelationshipImpl(); + relationshipImpl.setType(RELATIONSHIP_TYPE); + relationInfo.setRelationships(relationshipImpl); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java new file mode 100644 index 0000000000..a9245d2897 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java @@ -0,0 +1,402 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.api.AuditEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent; +import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent; +import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent; +import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESC_ERROR; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_LAST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_500; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID; +import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentsUtilsTest { + + private static User modifier = new User(); + private Component service = new Service(); + private Resource resource = new Resource(); + + @Mock + private AuditingManager manager; + + @Mock + private ResponseFormat responseFormat; + + @Captor + private ArgumentCaptor factoryCaptor; + + @InjectMocks + private static ComponentsUtils utils; + + @BeforeClass + public static void setUpClass() { + modifier.setFirstName(MODIFIER_FIRST_NAME); + modifier.setLastName(MODIFIER_LAST_NAME); + modifier.setUserId(MODIFIER_ID); + } + + + @Before + public void setUp() { + ThreadLocalsHolder.setUuid(REQUEST_ID); + utils = new ComponentsUtils(manager); + } + + @Test + public void auditComponentWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .state(CURRENT_STATE) + .version(CURRENT_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + } + + @Test + public void auditComponentWhenAllParamsPassedAndMostFromComponent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build(), + RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, true, true, true); + + } + + @Test + public void auditComponentDistStateWithoutArtDataCommentAndDid() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, service.getComponentType(), + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DPREV_STATUS).build(), + ResourceAuditData.newBuilder() + .artifactUuid(ARTIFACT_UUID) + .distributionStatus(DCURR_STATUS).build()); + verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), + STATUS_OK, DESCRIPTION, service.getComponentType().getValue(), + false, true, true, false, false, true); + } + + @Test + public void auditComponentWhenError() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setName(RESOURCE_NAME); + service.setVersion(CURRENT_VERSION); + + utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE, + ComponentTypeEnum.SERVICE, + ResourceAuditData.newBuilder().state(PREV_RESOURCE_STATE).version(PREV_RESOURCE_VERSION).artifactUuid(ARTIFACT_UUID).build()); + verifyResourceAdminEvent(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName(), STATUS_500, DESC_ERROR, + service.getComponentType().getValue(), false, true, false, false, false, false); + } + + @Test + public void auditComponentWhenCompIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE, + RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT); + verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + true, false, false, false, true, false); + } + + @Test + public void auditComponentAdmin() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + service.setUUID(SERVICE_INSTANCE_ID); + service.setInvariantUUID(INVARIANT_UUID); + service.setName(RESOURCE_NAME); + service.setState(LifecycleStateEnum.CERTIFIED); + service.setVersion(CURRENT_VERSION); + utils.auditComponentAdmin(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType()); + verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenAllParamsPassed() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + resource.setToscaResourceName(TOSCA_NODE_TYPE); + utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE, + ResourceAuditData.newBuilder() + .state(PREV_RESOURCE_STATE) + .version(PREV_RESOURCE_VERSION) + .artifactUuid(ARTIFACT_UUID) + .build(), + ARTIFACT_UUID, ARTIFACT_DATA); + verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(), + false, true, true, true, false, false); + } + + @Test + public void auditResourceWithoutPrevFields() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + resource.setUUID(SERVICE_INSTANCE_ID); + resource.setInvariantUUID(INVARIANT_UUID); + resource.setName(RESOURCE_NAME); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setVersion(CURRENT_VERSION); + + utils.auditResource(responseFormat, modifier, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA); + verifyResourceAdminEvent(AuditingActionEnum.UPDATE_RESOURCE_METADATA.getName(), STATUS_500, DESC_ERROR, resource.getResourceType().name(), + false, false, false, false, false, false); + } + + @Test + public void auditResourceWhenResourceIsNull() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500)); + when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR); + + utils.auditResource(responseFormat, modifier, RESOURCE_NAME, AuditingActionEnum.CHECKOUT_RESOURCE); + verifyResourceAdminEvent(AuditingActionEnum.CHECKOUT_RESOURCE.getName(), STATUS_500, DESC_ERROR, ComponentTypeEnum.RESOURCE.getValue(), + true, false, false, false, false, false); + } + + @Test + public void auditUserAdminEvent() { + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + User userAfter = new User(); + userAfter.setFirstName(USER_FIRST_NAME); + userAfter.setUserId(USER_ID); + userAfter.setLastName(USER_LAST_NAME); + userAfter.setRole(TESTER_USER_ROLE); + userAfter.setEmail(USER_EMAIL); + + utils.auditAdminUserAction(AuditingActionEnum.ADD_USER, modifier, null, userAfter, responseFormat); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + UserAdminEvent event = (UserAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.ADD_USER.getName()); + assertThat(event.getUserBefore()).isNull(); + assertThat(event.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME); + } + + @Test + public void auditEcompOpEnvEvent() { + utils.auditEnvironmentEngine(AuditingActionEnum.CREATE_ENVIRONMENT, OP_ENV_ID, OP_ENV_TYPE, OP_ENV_ACTION, OP_ENV_NAME, TENANT_CONTEXT); + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + EcompOperationalEnvironmentEvent event = (EcompOperationalEnvironmentEvent)factory.getDbEvent(); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CREATE_ENVIRONMENT.getName()); + assertThat(event.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID); + assertThat(event.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE); + assertThat(event.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME); + assertThat(event.getOperationalEnvironmentAction()).isEqualTo(OP_ENV_ACTION); + assertThat(event.getTenantContext()).isEqualTo(TENANT_CONTEXT); + } + + @Test + public void auditDistrDownloadEvent(){ + when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK)); + when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION); + + utils.auditDistributionDownload(responseFormat, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL)); + + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + DistributionDownloadEvent event = (DistributionDownloadEvent)factory.getDbEvent(); + assertThat(event.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL); + assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID); + assertThat(event.getStatus()).isEqualTo(STATUS_OK); + assertThat(event.getDesc()).isEqualTo(DESCRIPTION); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName()); + } + + private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull, + boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided, + boolean isDistStatusProvided) { + verify(manager).auditEvent(factoryCaptor.capture()); + AuditEventFactory factory = factoryCaptor.getValue(); + ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent(); + assertThat(event.getModifier()).isEqualTo(MODIFIER_UID); + assertThat(event.getStatus()).isEqualTo(status); + assertThat(event.getDesc()).isEqualTo(desc); + assertThat(event.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(event.getAction()).isEqualTo(action); + assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME); + + if (isComponentNull) { + assertThat(event.getServiceInstanceId()).isNull(); + assertThat(event.getCurrState()).isNull(); + assertThat(event.getCurrVersion()).isNull(); + assertThat(event.getInvariantUUID()).isNull(); + assertThat(event.getResourceType()).isEqualTo(resourceType); + } + else { + assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID); + assertThat(event.getCurrState()).isEqualTo(CURRENT_STATE); + assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION); + assertThat(event.getInvariantUUID()).isEqualTo(INVARIANT_UUID); + } + if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) { + assertThat(event.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE); + } + else { + assertThat(event.getToscaNodeType()).isEmpty(); + } + if (isPrevStateAndVersionSet) { + assertThat(event.getPrevState()).isEqualTo(PREV_RESOURCE_STATE); + assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION); + assertThat(event.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getPrevState()).isNull(); + assertThat(event.getPrevVersion()).isNull(); + assertThat(event.getPrevArtifactUUID()).isNull(); + } + if (isCurrFieldsProvided) { + assertThat(event.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID); + } + else { + assertThat(event.getCurrArtifactUUID()).isNull(); + } + if (isArtDataProvided) { + assertThat(event.getArtifactData()).isEqualTo(ARTIFACT_DATA); + if (resourceType.equals(ResourceTypeEnum.VFC.name())) { + assertThat(event.getDid()).isNull(); + } + else { + assertThat(event.getDid()).isEqualTo(DIST_ID); + } + } + else { + assertThat(event.getArtifactData()).isNull(); + assertThat(event.getDid()).isNull(); + } + if (isCommentProvided) { + assertThat(event.getComment()).isEqualTo(COMMENT); + } + else { + assertThat(event.getComment()).isEmpty(); + } + if (isDistStatusProvided) { + assertThat(event.getDcurrStatus()).isEqualTo(DCURR_STATUS); + assertThat(event.getDprevStatus()).isEqualTo(DPREV_STATUS); + } + else { + assertThat(event.getDcurrStatus()).isNull(); + assertThat(event.getDprevStatus()).isNull(); + } + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java index 4f1f929382..7b37b0e96a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java @@ -20,7 +20,13 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.unittests.utils.FactoryUtils; import java.util.ArrayList; import java.util.HashMap; @@ -29,126 +35,120 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.unittests.utils.FactoryUtils; +import static org.junit.Assert.assertTrue; public class CompositionBusinessLogicTest { - CompositionBusinessLogic compBl = new CompositionBusinessLogic(); - - @Test - public void testBuildSpiralPatternPositioningForComponentInstances() { - int instancesNum = 10; - Resource createVF = FactoryUtils.createVF(); - for (int i = 0; i < instancesNum; i++) { - FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); - } - Map, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); - assertTrue(componentInstances.size() == instancesNum); - // Verify Spiral Pattern - ImmutablePair key; - key = new ImmutablePair<>(0D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, 0D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(0D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-1D, -1D); - assertTrue(componentInstances.containsKey(key)); - key = new ImmutablePair<>(-2D, -1D); - assertTrue(componentInstances.containsKey(key)); - } - - @Test - public void testGetCpsConnectedToVFC() { - List allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); - - Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - assertTrue(cpsConnectedToVFC.size() == 1); - assertTrue(cpsConnectedToVFC.containsKey(vfc)); - Set cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); - assertTrue(cps.size() == 3); - cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); - - } - - @Test - public void testBuildCirclePatternForCps() { - List allComponentInstances = new ArrayList<>(); - Resource createVF = FactoryUtils.createVF(); - ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); - Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); - - Map, ComponentInstance> componentInstLocations = new HashMap<>(); - componentInstLocations.put(new ImmutablePair(0D, 0D), vfcInstance); - compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); - assertTrue(componentInstLocations.size() == 4); - - Set> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); - // Verify that all cps are located at different positions - assertTrue(cpsLocations.size() == 3); - Set distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); - // Verify that all cps are at the same distance from center - assertTrue(distances.size() == 1); - - } - - /** - * Adds 4 instances to the vf.
- * vfc instance and 3 cps instances.
- * the cp instances are connected to the vfc instance.
- * - * @param allComponentInstances - * @param createVF - * @return vfc instance - */ - private ComponentInstance populateVfWithVfcAndCps(List allComponentInstances, Resource createVF) { - ComponentInstance vfc = FactoryUtils.createResourceInstance(); - vfc.setOriginType(OriginTypeEnum.VFC); - FactoryUtils.addComponentInstanceToVF(createVF, vfc); - allComponentInstances.add(vfc); - - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - connectCpToVfc(allComponentInstances, createVF, vfc); - return vfc; - } - - private void connectCpToVfc(List allComponentInstances, Resource createVF, ComponentInstance vfc) { - List allRelations; - if (createVF.getComponentInstancesRelations() != null) { - allRelations = createVF.getComponentInstancesRelations(); - } else { - allRelations = new ArrayList<>(); - createVF.setComponentInstancesRelations(allRelations); - } - ComponentInstance cp1 = FactoryUtils.createResourceInstance(); - cp1.setOriginType(OriginTypeEnum.CP); - addVfcCpRelation(vfc, cp1, allRelations); - FactoryUtils.addComponentInstanceToVF(createVF, cp1); - allComponentInstances.add(cp1); - } - - private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List allRelations) { - RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); - rel.setToNode(vfc.getComponentUid()); - rel.setFromNode(cp.getComponentUid()); - allRelations.add(rel); - } + CompositionBusinessLogic compBl = new CompositionBusinessLogic(); + + @Test + public void testBuildSpiralPatternPositioningForComponentInstances() { + int instancesNum = 10; + Resource createVF = FactoryUtils.createVF(); + for (int i = 0; i < instancesNum; i++) { + FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance()); + } + Map, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF); + assertTrue(componentInstances.size() == instancesNum); + // Verify Spiral Pattern + ImmutablePair key; + key = new ImmutablePair<>(0D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, 0D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(0D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-1D, -1D); + assertTrue(componentInstances.containsKey(key)); + key = new ImmutablePair<>(-2D, -1D); + assertTrue(componentInstances.containsKey(key)); + } + + @Test + public void testGetCpsConnectedToVFC() { + List allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF); + + Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + assertTrue(cpsConnectedToVFC.size() == 1); + assertTrue(cpsConnectedToVFC.containsKey(vfc)); + Set cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet()); + assertTrue(cps.size() == 3); + cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP)); + + } + + @Test + public void testBuildCirclePatternForCps() { + List allComponentInstances = new ArrayList<>(); + Resource createVF = FactoryUtils.createVF(); + ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF); + Map> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF); + + Map, ComponentInstance> componentInstLocations = new HashMap<>(); + componentInstLocations.put(new ImmutablePair(0D, 0D), vfcInstance); + compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC); + assertTrue(componentInstLocations.size() == 4); + + Set> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet()); + // Verify that all cps are located at different positions + assertTrue(cpsLocations.size() == 3); + Set distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet()); + // Verify that all cps are at the same distance from center + assertTrue(distances.size() == 1); + + } + + /** + * Adds 4 instances to the vf.
+ * vfc instance and 3 cps instances.
+ * the cp instances are connected to the vfc instance.
+ * + * @param allComponentInstances + * @param createVF + * @return vfc instance + */ + private ComponentInstance populateVfWithVfcAndCps(List allComponentInstances, Resource createVF) { + ComponentInstance vfc = FactoryUtils.createResourceInstance(); + vfc.setOriginType(OriginTypeEnum.VFC); + FactoryUtils.addComponentInstanceToVF(createVF, vfc); + allComponentInstances.add(vfc); + + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + connectCpToVfc(allComponentInstances, createVF, vfc); + return vfc; + } + + private void connectCpToVfc(List allComponentInstances, Resource createVF, ComponentInstance vfc) { + List allRelations; + if (createVF.getComponentInstancesRelations() != null) { + allRelations = createVF.getComponentInstancesRelations(); + } else { + allRelations = new ArrayList<>(); + createVF.setComponentInstancesRelations(allRelations); + } + ComponentInstance cp1 = FactoryUtils.createResourceInstance(); + cp1.setOriginType(OriginTypeEnum.CP); + addVfcCpRelation(vfc, cp1, allRelations); + FactoryUtils.addComponentInstanceToVF(createVF, cp1); + allComponentInstances.add(cp1); + } + + private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List allRelations) { + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + rel.setToNode(vfc.getComponentUid()); + rel.setFromNode(cp.getComponentUid()); + allRelations.add(rel); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java index 50ad990560..d91fa7995b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java @@ -20,18 +20,18 @@ package org.openecomp.sdc.be.components.impl; -import java.util.Arrays; - import org.junit.Assert; import org.junit.Test; +import java.util.Arrays; + public class CsarValidationUtilsTest { - private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; - private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; + private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" }; + private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" }; - @Test - public void testIsCsarPayloadName() { - Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); - Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); - } + @Test + public void testIsCsarPayloadName() { + Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e))); + Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e))); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java new file mode 100644 index 0000000000..46ee852aa0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.be.resources.data.ServiceMetadataData; +import org.openecomp.sdc.be.resources.data.category.CategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * Created by chaya on 12/7/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class ElementBLTest { + + private static final String CATAGORY_NAME = "categoryName"; + private static final String CATEGORY_UNIQUE_ID = "catUniqueId"; + private static final String SERVICE_NOT_DELETED_ID = "notDeletedId"; + private static final String DELETED_SERVICE_ID = "deletedId"; + private List categories = new ArrayList<>(); + private List> services = new ArrayList<>(); + private List> resources = new ArrayList<>(); + private Service notDeletedService = new Service(); + private Resource notDeletedResource = new Resource(); + + @Mock + private TitanGenericDao titanGenericDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private TitanDao titanDao; + + @InjectMocks + private ElementBusinessLogic elementBusinessLogic; + + @Before + public void setup() { + + initCategoriesList(); + initServicesList(); + initResourceslist(); + + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void initCategoriesList() { + CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory); + categoryData.getCategoryDataDefinition().setUniqueId(CATEGORY_UNIQUE_ID); + categories.add(categoryData); + } + + private void initServicesList() { + ServiceMetadataData serviceNotDeleted = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition1 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition1.setIsDeleted(false); + componentMetadataDataDefinition1.setHighestVersion(true); + componentMetadataDataDefinition1.setUniqueId(SERVICE_NOT_DELETED_ID); + serviceNotDeleted.setMetadataDataDefinition(componentMetadataDataDefinition1); + services.add(new ImmutablePair<>(serviceNotDeleted, null)); + + ServiceMetadataData deletedService = new ServiceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition2 = new ServiceMetadataDataDefinition(); + componentMetadataDataDefinition2.setIsDeleted(true); + componentMetadataDataDefinition2.setHighestVersion(true); + componentMetadataDataDefinition2.setUniqueId(DELETED_SERVICE_ID); + deletedService.setMetadataDataDefinition(componentMetadataDataDefinition2); + services.add(new ImmutablePair<>(deletedService, null)); + } + + private void initResourceslist() { + ResourceMetadataData notDeletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition3 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition3.setIsDeleted(false); + componentMetadataDataDefinition3.setHighestVersion(true); + componentMetadataDataDefinition3.setUniqueId(SERVICE_NOT_DELETED_ID); + notDeletedResource.setMetadataDataDefinition(componentMetadataDataDefinition3); + resources.add(new ImmutablePair<>(notDeletedResource, null)); + + ResourceMetadataData deletedResource = new ResourceMetadataData(); + ComponentMetadataDataDefinition componentMetadataDataDefinition4 = new ResourceMetadataDataDefinition(); + componentMetadataDataDefinition4.setIsDeleted(true); + componentMetadataDataDefinition4.setHighestVersion(true); + componentMetadataDataDefinition4.setUniqueId(DELETED_SERVICE_ID); + deletedResource.setMetadataDataDefinition(componentMetadataDataDefinition4); + resources.add(new ImmutablePair<>(deletedResource, null)); + } + + @Test + public void testFetchElementsByCategoryName_filterDeleted() { + ArgumentCaptor criteriaCapture = ArgumentCaptor.forClass(Map.class); + + when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class))) + .thenReturn(Either.left(categories)); + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class)) + .thenReturn(Either.left(services)); + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedService)); + + Either, StorageOperationStatus> elementsByCategoryEither = + elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), + NodeTypeEnum.Service, false, ServiceMetadataData.class, null); + + List elementsByCategory = elementsByCategoryEither.left().value(); + assertThat(elementsByCategory.get(0)).isSameAs(notDeletedService); + assertThat(elementsByCategory.size()).isEqualTo(1); + verifyCriteriaProperties(criteriaCapture); + } + + private void verifyCriteriaProperties(ArgumentCaptor propsCapture) { + Map props = propsCapture.getValue(); + assertThat(props.size()).isEqualTo(1); + assertThat(props.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty())).isEqualTo(ValidationUtils.normalizeCategoryName4Uniqueness(CATAGORY_NAME)); + } + + @Test + public void testFetchResourcesBySubcategoryUid_filterDeleted() { + + when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), + CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)) + .thenReturn(Either.left(resources)); + + when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata)) + .thenReturn(Either.left(notDeletedResource)); + + Either, StorageOperationStatus> resourcesBySubCategoryUidEither = elementBusinessLogic.fetchByCategoryOrSubCategoryUid(CATEGORY_UNIQUE_ID, NodeTypeEnum.ResourceSubcategory, + GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, false, ResourceMetadataData.class, null); + List resourcesBySubCategoryUid = resourcesBySubCategoryUidEither.left().value(); + assertThat(resourcesBySubCategoryUid.size()).isEqualTo(1); + assertThat(resourcesBySubCategoryUid.get(0)).isSameAs(notDeletedResource); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 5edf448cc2..b65e77c57f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -20,21 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import fj.data.Either; import org.junit.Test; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; @@ -46,462 +32,475 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.yaml.snakeyaml.Yaml; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ImportUtilsTest { - @Test - public void testStringTypeFindToscaElements() throws IOException { - Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List list = toscaElements.left().value(); - assertTrue(list.size() == 4); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof String); - String value = (String) element; - assertTrue(value.equals("stringVal" + count)); - count++; - } - } - - @Test - public void testBooleanTypeFindToscaElements() throws IOException { - Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Boolean); - Boolean value = (Boolean) element; - if (count == 1 || count == 3) { - assertFalse(value); - } else if (count == 2) { - assertTrue(value); - } - - count++; - } - } - - @Test - public void testListTypeFindToscaElements() throws IOException { - Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List list = toscaElements.left().value(); - assertTrue(list.size() == 3); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof List); - - if (count == 1) { - verifyListElement1(element); - } else if (count == 2) { - verifyListElement2(element); - } - - else if (count == 3) { - verifyListElement3(element); - } - count++; - } - } - - @Test - public void testAllTypeFindToscaElements() throws IOException { - Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List list = toscaElements.left().value(); - assertTrue(list.size() == 5); - int count = 1; - for (Object element : list) { - if (count == 1) { - assertTrue(element instanceof String); - assertTrue(element.equals("tosca.nodes.Root")); - } else if (count == 2) { - assertTrue(element instanceof Map); - Map mapElement = (Map) element; - assertTrue(mapElement.size() == 2); - Iterator> elementEntries = mapElement.entrySet().iterator(); - Entry elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("mapTestTag")); - assertTrue(elementEntry.getValue().equals("string")); - - elementEntry = elementEntries.next(); - assertTrue(elementEntry.getKey().equals("required")); - assertTrue(elementEntry.getValue() instanceof Boolean); - assertTrue((Boolean) elementEntry.getValue()); - } - - else if (count == 3) { - assertTrue(element instanceof String); - assertTrue(element.equals("1 MB")); - } - - else if (count == 4) { - assertTrue(element instanceof List); - List listElement = (List) element; - assertTrue(listElement.size() == 2); - - assertTrue(listElement.get(0) instanceof Map); - Map innerElement = (Map) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("greater_or_equal")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal3")); - } else if (count == 5) { - assertTrue(element instanceof Boolean); - assertFalse((Boolean) element); - } - count++; - } - } - - @Test - public void testMapTypeFindToscaElements() throws IOException { - Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); - assertTrue(toscaElements.isLeft()); - List list = toscaElements.left().value(); - assertTrue(list.size() == 2); - int count = 1; - for (Object element : list) { - assertTrue(element instanceof Map); - - if (count == 1) { - Map mapElement = (Map) element; - assertTrue(mapElement.size() == 2); - Iterator> iterator = mapElement.entrySet().iterator(); - Entry inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("stringTestTag")); - assertTrue(inerElementEntry.getValue().equals("stringVal1")); - - inerElementEntry = iterator.next(); - assertTrue(inerElementEntry.getKey().equals("listTestTag")); - assertTrue(inerElementEntry.getValue() instanceof List); - List innerValue = (List) inerElementEntry.getValue(); - - assertTrue(innerValue.size() == 3); - - } else if (count == 2) { - Map mapElement = (Map) element; - assertTrue(mapElement.size() == 2); - Iterator> entryItr = mapElement.entrySet().iterator(); - Entry inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("type")); - assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); - inerElementEntry = entryItr.next(); - assertTrue(inerElementEntry.getKey().equals("allTestTag")); - assertTrue(inerElementEntry.getValue() instanceof Boolean); - } - - count++; - } - } - - @Test - public void testCreateFullHeatParameterModuleWithString() { - - testCreateFullHeatParameterModule("string", "default value"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithNumber() { - - testCreateFullHeatParameterModule("number", "777"); - testCreateFullHeatParameterModule("number", "777.23"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithBoolean() { - - testCreateFullHeatParameterModule("boolean", "true"); - testCreateFullHeatParameterModule("boolean", "on"); - testCreateFullHeatParameterModule("boolean", "n"); - - } - - @Test - public void testCreateFullHeatParameterModuleWithList() { - - testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); - - } - - // @Test - // public void testCreateFullHeatParameterModuleWithInvalidType(){ - // - // String name = "fullParameter"; - // String description = "description_text"; - // - // Map parametersMap = new HashMap(); - // Map firstParam = createParameterMap("aaa", "aaa", - // name, description); - // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), - // firstParam); - // - // Either,ResultStatusEnum> heatParameters = - // ImportUtils.getHeatParameters(parametersMap); - // assertTrue(heatParameters.isRight()); - // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, - // heatParameters.right().value()); - // - // } - - @Test - public void testCreateFullHeatParameterModuleWithMissingType() { - - String name = "fullParameter"; - String description = "description_text"; - - Map parametersMap = new HashMap(); - Map firstParam = createParameterMap(null, "aaa", name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isRight()); - assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); + @Test + public void testStringTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 4); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof String); + String value = (String) element; + assertTrue(value.equals("stringVal" + count)); + count++; + } + } + + @Test + public void testBooleanTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Boolean); + Boolean value = (Boolean) element; + if (count == 1 || count == 3) { + assertFalse(value); + } else if (count == 2) { + assertTrue(value); + } + + count++; + } + } + + @Test + public void testListTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 3); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof List); + + if (count == 1) { + verifyListElement1(element); + } else if (count == 2) { + verifyListElement2(element); + } + + else if (count == 3) { + verifyListElement3(element); + } + count++; + } + } + + @Test + public void testAllTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 5); + int count = 1; + for (Object element : list) { + if (count == 1) { + assertTrue(element instanceof String); + assertTrue(element.equals("tosca.nodes.Root")); + } else if (count == 2) { + assertTrue(element instanceof Map); + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> elementEntries = mapElement.entrySet().iterator(); + Entry elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("mapTestTag")); + assertTrue(elementEntry.getValue().equals("string")); + + elementEntry = elementEntries.next(); + assertTrue(elementEntry.getKey().equals("required")); + assertTrue(elementEntry.getValue() instanceof Boolean); + assertTrue((Boolean) elementEntry.getValue()); + } + + else if (count == 3) { + assertTrue(element instanceof String); + assertTrue(element.equals("1 MB")); + } + + else if (count == 4) { + assertTrue(element instanceof List); + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + assertTrue(listElement.get(0) instanceof Map); + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("greater_or_equal")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal3")); + } else if (count == 5) { + assertTrue(element instanceof Boolean); + assertFalse((Boolean) element); + } + count++; + } + } + + @Test + public void testMapTypeFindToscaElements() throws IOException { + Either, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>()); + assertTrue(toscaElements.isLeft()); + List list = toscaElements.left().value(); + assertTrue(list.size() == 2); + int count = 1; + for (Object element : list) { + assertTrue(element instanceof Map); + + if (count == 1) { + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> iterator = mapElement.entrySet().iterator(); + Entry inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("stringTestTag")); + assertTrue(inerElementEntry.getValue().equals("stringVal1")); + + inerElementEntry = iterator.next(); + assertTrue(inerElementEntry.getKey().equals("listTestTag")); + assertTrue(inerElementEntry.getValue() instanceof List); + List innerValue = (List) inerElementEntry.getValue(); + + assertTrue(innerValue.size() == 3); + + } else if (count == 2) { + Map mapElement = (Map) element; + assertTrue(mapElement.size() == 2); + Iterator> entryItr = mapElement.entrySet().iterator(); + Entry inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("type")); + assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment")); + inerElementEntry = entryItr.next(); + assertTrue(inerElementEntry.getKey().equals("allTestTag")); + assertTrue(inerElementEntry.getValue() instanceof Boolean); + } + + count++; + } + } + + @Test + public void testCreateFullHeatParameterModuleWithString() { + + testCreateFullHeatParameterModule("string", "default value"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithNumber() { + + testCreateFullHeatParameterModule("number", "777"); + testCreateFullHeatParameterModule("number", "777.23"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithBoolean() { + + testCreateFullHeatParameterModule("boolean", "true"); + testCreateFullHeatParameterModule("boolean", "on"); + testCreateFullHeatParameterModule("boolean", "n"); + + } + + @Test + public void testCreateFullHeatParameterModuleWithList() { + + testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]"); + + } + + // @Test + // public void testCreateFullHeatParameterModuleWithInvalidType(){ + // + // String name = "fullParameter"; + // String description = "description_text"; + // + // Map parametersMap = new HashMap(); + // Map firstParam = createParameterMap("aaa", "aaa", + // name, description); + // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), + // firstParam); + // + // Either,ResultStatusEnum> heatParameters = + // ImportUtils.getHeatParameters(parametersMap); + // assertTrue(heatParameters.isRight()); + // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, + // heatParameters.right().value()); + // + // } + + @Test + public void testCreateFullHeatParameterModuleWithMissingType() { + + String name = "fullParameter"; + String description = "description_text"; + + Map parametersMap = new HashMap(); + Map firstParam = createParameterMap(null, "aaa", name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isRight()); + assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value()); - } + } - @Test - public void testCreateFullHeatParameterModuleWithMissingFields() { + @Test + public void testCreateFullHeatParameterModuleWithMissingFields() { - String name = "fullParameter"; + String name = "fullParameter"; - Map parametersMap = new HashMap(); - String type = "number"; - String defValue = "defvalue"; - // default value cannot be empty in heat in case tag exists - Map firstParam = createParameterMap(type, defValue, name, null); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + Map parametersMap = new HashMap(); + String type = "number"; + String defValue = "defvalue"; + // default value cannot be empty in heat in case tag exists + Map firstParam = createParameterMap(type, defValue, name, null); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - assertParameter(parameterDefinition, name, type, null, defValue); + assertParameter(parameterDefinition, name, type, null, defValue); - } + } - @Test - public void testGetAttributesFromYml() throws IOException { + @Test + public void testGetAttributesFromYml() throws IOException { - Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); - Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); - assertTrue(actualAttributes.isLeft()); - Map> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); - compareAttributes(expectedAttributes, actualAttributes.left().value()); + Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); + Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + assertTrue(actualAttributes.isLeft()); + Map> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); + compareAttributes(expectedAttributes, actualAttributes.left().value()); - } + } - @Test - public void testGetPropertiesFromYml() throws IOException { + @Test + public void testGetPropertiesFromYml() throws IOException { - Map toscaJson = (Map) loadJsonFromFile("importToscaProperties.yml"); - Either, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); - assertTrue(actualProperties.isLeft()); - Map> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); - compareProperties(expectedProperties, actualProperties.left().value()); + Map toscaJson = (Map) loadJsonFromFile("importToscaProperties.yml"); + Either, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson); + assertTrue(actualProperties.isLeft()); + Map> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES); + compareProperties(expectedProperties, actualProperties.left().value()); - } + } - private void compareAttributes(Map> expected, Map actual) { + private void compareAttributes(Map> expected, Map actual) { - Map singleExpectedAttribute; - PropertyDefinition actualAttribute, expectedAttributeModel; - // attributes of resource - for (Map.Entry> expectedAttribute : expected.entrySet()) { + Map singleExpectedAttribute; + PropertyDefinition actualAttribute, expectedAttributeModel; + // attributes of resource + for (Map.Entry> expectedAttribute : expected.entrySet()) { - singleExpectedAttribute = expectedAttribute.getValue(); - assertNotNull(singleExpectedAttribute); - actualAttribute = actual.get(expectedAttribute.getKey()); - assertNotNull(actualAttribute); - actualAttribute.setName(expectedAttribute.getKey().toString()); - expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); - expectedAttributeModel.setName(expectedAttribute.getKey().toString()); + singleExpectedAttribute = expectedAttribute.getValue(); + assertNotNull(singleExpectedAttribute); + actualAttribute = actual.get(expectedAttribute.getKey()); + assertNotNull(actualAttribute); + actualAttribute.setName(expectedAttribute.getKey().toString()); + expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); + expectedAttributeModel.setName(expectedAttribute.getKey().toString()); - assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); - assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); - assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); - assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); - assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); + assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); + assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); + assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); + assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); - compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); + compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); - } + } - } + } - private void compareProperties(Map> expected, Map actual) { + private void compareProperties(Map> expected, Map actual) { - Map singleExpectedProperty; - PropertyDefinition actualProperty, expectedPropertyModel; - // attributes of resource - for (Map.Entry> expectedProperty : expected.entrySet()) { + Map singleExpectedProperty; + PropertyDefinition actualProperty, expectedPropertyModel; + // attributes of resource + for (Map.Entry> expectedProperty : expected.entrySet()) { - singleExpectedProperty = expectedProperty.getValue(); - assertNotNull(singleExpectedProperty); - actualProperty = actual.get(expectedProperty.getKey()); - assertNotNull(actualProperty); - actualProperty.setName(expectedProperty.getKey().toString()); - expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); - expectedPropertyModel.setName(expectedProperty.getKey().toString()); + singleExpectedProperty = expectedProperty.getValue(); + assertNotNull(singleExpectedProperty); + actualProperty = actual.get(expectedProperty.getKey()); + assertNotNull(actualProperty); + actualProperty.setName(expectedProperty.getKey().toString()); + expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty); + expectedPropertyModel.setName(expectedProperty.getKey().toString()); - assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); - assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); - assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); - assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); - assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); + assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue()); + assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription()); + assertEquals(expectedPropertyModel.getName(), actualProperty.getName()); + assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus()); + assertEquals(expectedPropertyModel.getType(), actualProperty.getType()); - compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); + compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema()); - } + } - } + } - private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { + private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) { - if (expected == null && actual == null) { - return; - } - PropertyDataDefinition actualPropertySchema = actual.getProperty(); - PropertyDataDefinition expectedPropertySchema = expected.getProperty(); - assertNotNull(actualPropertySchema); - assertNotNull(expectedPropertySchema); - assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); - assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); - - } + if (expected == null && actual == null) { + return; + } + PropertyDataDefinition actualPropertySchema = actual.getProperty(); + PropertyDataDefinition expectedPropertySchema = expected.getProperty(); + assertNotNull(actualPropertySchema); + assertNotNull(expectedPropertySchema); + assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription()); + assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType()); + + } - private Map getElements(Map toscaJson, ToscaTagNamesEnum elementType) { - - Either, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); - assertTrue(toscaExpectedElements.isLeft()); - - return toscaExpectedElements.left().value(); - - } - - private void testCreateFullHeatParameterModule(String type, Object defaultVal) { - - String name = "fullParameter"; - String description = "description_text"; - - Map parametersMap = new HashMap(); - Map firstParam = createParameterMap(type, defaultVal, name, description); - parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); - - Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); - assertTrue(heatParameters.isLeft()); - List parameterDefList = heatParameters.left().value(); - assertFalse(parameterDefList.isEmpty()); - HeatParameterDefinition parameterDefinition = parameterDefList.get(0); - - assertParameter(parameterDefinition, name, type, description, defaultVal); - - } - - private Map createParameterMap(String type, Object defaultVal, String name, String description) { - Map firstParam = new HashMap(); - Map valuesMap = new HashMap(); - - valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); - valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); - valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); - - firstParam.put(name, valuesMap); - return firstParam; - } - - private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { - assertEquals(name, parameterDefinition.getName()); - assertEquals(description, parameterDefinition.getDescription()); - assertEquals(type, parameterDefinition.getType()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); - assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); - } - - private void verifyListElement3(Object element) { - List listElement = (List) element; - assertTrue(listElement.size() == 2); - - Map innerElement = (Map) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("type")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - private void verifyListElement2(Object element) { - List listElement = (List) element; - assertTrue(listElement.size() == 2); - - Map innerElement = (Map) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("testTag1")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - assertTrue(listElement.get(1) instanceof Map); - innerElement = (Map) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue() instanceof List); - } - - private void verifyListElement1(Object element) { - List listElement = (List) element; - assertTrue(listElement.size() == 3); - - Map innerElement = (Map) listElement.get(0); - assertTrue(innerElement.size() == 1); - Entry innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("1 MB")); - - innerElement = (Map) listElement.get(1); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("listTestTag")); - assertTrue(innerEntry.getValue().equals("2 MB")); - - innerElement = (Map) listElement.get(2); - assertTrue(innerElement.size() == 1); - innerEntry = innerElement.entrySet().iterator().next(); - assertTrue(innerEntry.getKey().equals("stringTestTag")); - assertTrue(innerEntry.getValue().equals("stringVal2")); - } - - public static String loadFileNameToJsonString(String fileName) throws IOException { - String sourceDir = "src/test/resources/normativeTypes"; - java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); - byte[] fileContent = Files.readAllBytes(filePath); - String content = new String(fileContent); - return content; - } - - private static Object loadJsonFromFile(String fileName) throws IOException { - String content = loadFileNameToJsonString(fileName); - Object load = new Yaml().load(content); - return load; - } + private Map getElements(Map toscaJson, ToscaTagNamesEnum elementType) { + + Either, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType); + assertTrue(toscaExpectedElements.isLeft()); + + return toscaExpectedElements.left().value(); + + } + + private void testCreateFullHeatParameterModule(String type, Object defaultVal) { + + String name = "fullParameter"; + String description = "description_text"; + + Map parametersMap = new HashMap(); + Map firstParam = createParameterMap(type, defaultVal, name, description); + parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam); + + Either, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType()); + assertTrue(heatParameters.isLeft()); + List parameterDefList = heatParameters.left().value(); + assertFalse(parameterDefList.isEmpty()); + HeatParameterDefinition parameterDefinition = parameterDefList.get(0); + + assertParameter(parameterDefinition, name, type, description, defaultVal); + + } + + private Map createParameterMap(String type, Object defaultVal, String name, String description) { + Map firstParam = new HashMap(); + Map valuesMap = new HashMap(); + + valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type); + valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description); + valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal); + + firstParam.put(name, valuesMap); + return firstParam; + } + + private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) { + assertEquals(name, parameterDefinition.getName()); + assertEquals(description, parameterDefinition.getDescription()); + assertEquals(type, parameterDefinition.getType()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue()); + assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue()); + } + + private void verifyListElement3(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("type")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + private void verifyListElement2(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 2); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("testTag1")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + assertTrue(listElement.get(1) instanceof Map); + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue() instanceof List); + } + + private void verifyListElement1(Object element) { + List listElement = (List) element; + assertTrue(listElement.size() == 3); + + Map innerElement = (Map) listElement.get(0); + assertTrue(innerElement.size() == 1); + Entry innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("1 MB")); + + innerElement = (Map) listElement.get(1); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("listTestTag")); + assertTrue(innerEntry.getValue().equals("2 MB")); + + innerElement = (Map) listElement.get(2); + assertTrue(innerElement.size() == 1); + innerEntry = innerElement.entrySet().iterator().next(); + assertTrue(innerEntry.getKey().equals("stringTestTag")); + assertTrue(innerEntry.getValue().equals("stringVal2")); + } + + public static String loadFileNameToJsonString(String fileName) throws IOException { + String sourceDir = "src/test/resources/normativeTypes"; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static Object loadJsonFromFile(String fileName) throws IOException { + String content = loadFileNameToJsonString(fileName); + Object load = new Yaml().load(content); + return load; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index ac4d37ef76..068f04aae2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -20,21 +20,14 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ComponentInstance; @@ -46,7 +39,17 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.user.IUserBusinessLogic; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class InputsBusinessLogicTest { @@ -63,6 +66,9 @@ public class InputsBusinessLogicTest { @Mock private ToscaOperationFacade toscaOperationFacadeMock; + @Mock + private UserValidations userValidations; + @InjectMocks private InputsBusinessLogic testInstance; @@ -83,13 +89,13 @@ public class InputsBusinessLogicTest { instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput)); instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput())); service.setComponentInstancesInputs(instanceInputMap); - - Mockito.when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User())); } @Test public void getComponentInstanceInputs_ComponentInstanceNotExist() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, "nonExisting"); assertTrue(componentInstanceInputs.isRight()); Mockito.verify(componentsUtilsMock).getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); @@ -115,13 +121,13 @@ public class InputsBusinessLogicTest { @Test public void getComponentInstanceInputs() throws Exception { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals("inputId", componentInstanceInputs.left().value().get(0).getInputId()); } private void getComponents_emptyInputs(Service service) { - Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service)); Either, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID); assertEquals(Collections.emptyList(), componentInstanceInputs.left().value()); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java index 8109e36be1..e726f608f5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -42,51 +34,54 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import fj.data.Either; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; -public class InterfaceLifecycleTypeImportManagerTest { +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; - @InjectMocks - private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); - public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); - public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); +public class InterfaceLifecycleTypeImportManagerTest { - static Logger log = Mockito.spy(Logger.class); + @InjectMocks + private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager(); + public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class); + public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - @BeforeClass - public static void beforeClass() throws IOException { - InterfaceLifecycleTypeImportManager.setLog(log); - when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer>() { - public Either answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Either ans = Either.left((InterfaceDefinition) args[0]); - return ans; - } + @BeforeClass + public static void beforeClass() throws IOException { + when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer>() { + public Either answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Either ans = Either.left((InterfaceDefinition) args[0]); + return ans; + } - }); - when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); - } + }); + when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod(); + } - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + } - @Test - public void importLiecycleTest() throws IOException { - String ymlContent = getYmlContent(); - Either, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); - assertTrue(createCapabilityTypes.isLeft()); + @Test + public void importLiecycleTest() throws IOException { + String ymlContent = getYmlContent(); + Either, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent); + assertTrue(createCapabilityTypes.isLeft()); - } + } - private String getYmlContent() throws IOException { - Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); - byte[] fileContent = Files.readAllBytes(filePath); - String ymlContent = new String(fileContent); - return ymlContent; - } + private String getYmlContent() throws IOException { + Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml"); + byte[] fileContent = Files.readAllBytes(filePath); + String ymlContent = new String(fileContent); + return ymlContent; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java new file mode 100644 index 0000000000..9aca92010e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java @@ -0,0 +1,493 @@ +package org.openecomp.sdc.be.components.impl; + + +import fj.data.Either; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyBusinessLogicTest { + + @InjectMocks + private PolicyBusinessLogic businessLogic; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private UserValidations userValidations; + @Mock + private TitanDao titanDao; + @Mock + private ApplicationDataTypeCache dataTypeCache; + @Mock + private PropertyOperation propertyOperation; + + private final static String COMPONENT_ID = "componentId"; + private final static String COMPONENT_NAME = "componentName"; + private final static String POLICY_TYPE_NAME = "policyTypeName"; + private final static String POLICY_ID = "policyId"; + private final static String INVALID_POLICY_ID = "invalidPolicyId"; + private final static String POLICY_NAME = "policyName"; + private final static String OTHER_POLICY_NAME = "otherPolicyName"; + private final static String USER_ID = "jh0003"; + private final static String UNIQUE_ID_EXSISTS = "uniqueIdExists"; + private final static String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists"; + private final static String FAKE_TYPE = "fakeType"; + private final static String COMPONENT_INSTANCE_TYPE = "component_Instances"; + private final static String GROUP_TYPE = "GROUPS"; + + + + + private final String CREATE_POLICY = "create Policy"; + + private final static User user = buildUser(); + private final static PolicyDefinition policy = buildPolicy(POLICY_NAME); + private final static PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME); + private final static Resource resource = buildResource(); + private final static PolicyTypeDefinition policyType = buildPolicyType(); + + private static Either userSuccessEither; + private static Either componentSuccessEither; + private static Either getPolicyTypeSuccessEither; + private static Either policySuccessEither; + private static ResponseFormat notFoundResponse; + private static ResponseFormat invalidContentResponse; + private static ResponseFormat nameExistsResponse; + + @BeforeClass + public static void setup() { + String appConfigDir = "src/test/resources/config/catalog-be"; + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + createResponses(); + new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir)); + } + + private static void createResponses() { + userSuccessEither = Either.left(user); + componentSuccessEither = Either.left(resource); + getPolicyTypeSuccessEither = Either.left(policyType); + policySuccessEither = Either.left(policy); + notFoundResponse = new ResponseFormat(); + notFoundResponse.setStatus(404); + invalidContentResponse = new ResponseFormat(); + invalidContentResponse.setStatus(400); + nameExistsResponse = new ResponseFormat(); + nameExistsResponse.setStatus(409); + } + + @Test + public void createPolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void createPolicyUserFailureTest(){ + Either userNotFoundResponse = Either.right(new ResponseFormat(404)); + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userNotFoundResponse); + stubRollback(); + Either response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + private void assertNotFound(Either response) { + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void createPolicyComponentFailureTest(){ + when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither); + Either componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND); + when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(ComponentTypeEnum.RESOURCE))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse); + Either response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyPolicyTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + Either getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeFailed); + when(componentsUtils.convertFromStorageResponse(eq(getPolicyTypeFailed.right().value()))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + Either response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertNotFound(response); + } + + @Test + public void createPolicyComponentTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither); + Either addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST); + when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes); + when(componentsUtils.convertFromStorageResponse(eq(addPolicyRes.right().value()))).thenReturn(ActionStatus.INVALID_CONTENT); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_CONTENT))).thenReturn(invalidContentResponse); + stubUnlockAndRollback(); + Either response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(400)); + } + + @Test + public void updatePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + Either response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyNameFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NAME_ALREADY_EXIST), eq(POLICY_NAME))).thenReturn(nameExistsResponse); + stubUnlockAndRollback(); + Either response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(409)); + } + + @Test + public void getPolicySuccessTest(){ + stubValidationSuccess(CREATE_POLICY); + stubCommit(); + Either response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID); + assertTrue(response.isLeft()); + } + + @Test + public void getPolicyFailureTest(){ + stubValidationSuccess(CREATE_POLICY); + stubRollback(); + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), eq(INVALID_POLICY_ID), eq(COMPONENT_ID))).thenReturn(notFoundResponse); + Either response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + @Test + public void deletePolicySuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + when(toscaOperationFacade.removePolicyFromComponent(eq(COMPONENT_ID),eq(POLICY_ID))).thenReturn(StorageOperationStatus.OK); + Either response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void deletePolicyFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubCommit(); + stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER(); + Either response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true); + assertNotFound(response); + } + + private void stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), anyString(), anyString())).thenReturn(new ResponseFormat(404)); + } + + @Test + public void updatePolicyPropertiesSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + String prop1 = "Name"; + String prop2 = "Type"; + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1)); + when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2)); + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither); + stubUnlockAndCommit(); + PropertyDataDefinition[] properties = getProperties(prop1, prop2); + policy.setProperties(Arrays.asList(properties)); + Either, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties , USER_ID, true); + assertTrue(response.isLeft()); + } + + @Test + public void updatePolicyTargetsSuccessTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubGetToscaElementSuccess(); + stubGetTargetType(); + + Either result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID); + + Assert.assertTrue(result.isLeft()); + PolicyDefinition policyResult = result.left().value(); + Map> targets = getTargets(); + assertThat(policyResult.getTargets().values()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES)); + + } + + private void stubGetTargetType() { + } + + @Test + public void updatePolicyTargetsTargetIDFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeId(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertEquals(responseResult.getStatus().longValue(), 400L); + + } + + private void stubComponentUtilsGetResponseTargetNotFound() { + when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST), (anyString()))).thenReturn(new ResponseFormat(400)); + } + + @Test + public void updatePolicyTargetsTypeFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + stubGetToscaFullElementSuccess(); + stubGetToscaElementSuccess(); + stubUpdatePolicyOfComponentSuccess(); + stubComponentUtilsGetResponseTargetNotFound(); + stubRollback(); + + Either result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeType(), USER_ID); + + Assert.assertTrue(result.isRight()); + ResponseFormat responseResult = result.right().value(); + Assert.assertTrue(responseResult.getStatus().equals(400)); + + } + + private void stubUpdatePolicyOfComponentSuccess() { + when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy))).thenReturn(policySuccessEither); + } + + + @Test + public void updatePolicyPropertiesFailureTest(){ + stubValidateAndLockSuccess(CREATE_POLICY); + when(componentsUtils.getResponseFormat(eq(ActionStatus.PROPERTY_NOT_FOUND))).thenReturn(notFoundResponse); + stubUnlockAndRollback(); + policy.setProperties(null); + Either, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getProperties("Name", "Type") , USER_ID, true); + assertTrue(response.isRight() && response.right().value().getStatus().equals(404)); + } + + private PropertyDataDefinition[] getProperties(String prop1, String prop2) { + PropertyDataDefinition property1 = new PropertyDataDefinition(); + property1.setName(prop1); + property1.setValue(prop1); + PropertyDataDefinition property2 = new PropertyDataDefinition(); + property2.setName(prop2); + property2.setValue(prop2); + PropertyDataDefinition[] properties = {property1, property2}; + return properties; + } + + + private void stubUnlockAndRollback() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubRollback(); + } + + private void stubCommit() { + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } + + private void stubRollback() { + when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK); + } + + private void stubUnlockAndCommit() { + when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + stubCommit(); + } + + private void stubValidateAndLockSuccess(String methodName) { + stubValidationSuccess(methodName); + when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK); + } + + private void stubValidationSuccess(String methodName) { + when(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(userSuccessEither); + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither); + } + + private void stubGetToscaFullElementSuccess() { + when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(buildElementEither()); + } + + private void stubGetToscaElementSuccess() { + when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID))).thenReturn(componentSuccessEither); + } + + private Either buildElementEither() { + ResourceBuilder builder = new ResourceBuilder(); + GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build(); + ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder(); + ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build(); + return Either.left(builder.addGroups(groupDefinition).addComponentInstance(componentInstance).build()); + } + + private Map> getTargets() { + Map> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + + + private static PolicyTypeDefinition buildPolicyType() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + policyType.setType(POLICY_TYPE_NAME); + return policyType; + } + + private static PolicyDefinition buildPolicy(String policyName) { + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + policy.setPolicyTypeName(POLICY_TYPE_NAME); + policy.setComponentName(COMPONENT_NAME); + policy.setName(policyName); + return policy; + } + + private static Resource buildResource() { + Resource resource = new Resource(); + resource.setUniqueId(COMPONENT_ID); + resource.setName(COMPONENT_NAME); + resource.setCreatorUserId(USER_ID); + resource.setLastUpdaterUserId(USER_ID); + resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setResourceType(ResourceTypeEnum.VF); + resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); + Map policies = new HashMap<>(); + policies.put(POLICY_ID, policy); + resource.setPolicies(policies); + return resource; + } + + private static User buildUser() { + User user = new User(); + user.setUserId(USER_ID); + return user; + } + private List getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType("componentInstances"); + + return Arrays.asList(target1, target2); + } + + private List getFakeIDTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target1.setType(GROUP_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + target2.setType(COMPONENT_INSTANCE_TYPE); + + return Arrays.asList(target1, target2); + } + private List getFakeTypeTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target1.setType(FAKE_TYPE); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS)); + target2.setType(FAKE_TYPE); + + return Arrays.asList(target1, target2); + } + + private Map> getTargetListFakeType() { + Map> targets = new HashMap<>(); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS)); + return targets; + } + + private Map> getTargetListFakeId() { + Map> targets = new HashMap<>(); + targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS)); + return targets; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java new file mode 100644 index 0000000000..ad3e6e8974 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java @@ -0,0 +1,148 @@ +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.core.Response; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyPropertiesBusinessLogicTest { + + private static final String POLICY_ID = "policy1"; + private static final String RESOURCE_ID = "resourceId"; + private static final String USER_ID = "userId"; + public static final String NO_PROPS_POLICY = "policy2"; + @InjectMocks + private PolicyBusinessLogic testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private TitanDao titanDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private ComponentsUtils componentsUtils; + + private ComponentParametersView componentFilter; + private Resource resource; + private PropertyDefinition prop1, prop2; + + @Before + public void setUp() throws Exception { + componentFilter = new ComponentParametersView(true); + componentFilter.setIgnorePolicies(false); + componentFilter.setIgnoreUsers(false); + + prop1 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + prop2 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build(); + + PolicyDefinition policy1 = PolicyDefinitionBuilder.create() + .setUniqueId(POLICY_ID) + .setProperties(prop1, prop2) + .build(); + + PolicyDefinition policy2 = PolicyDefinitionBuilder.create() + .setUniqueId(NO_PROPS_POLICY) + .build(); + resource = new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) + .setLastUpdaterUserId(USER_ID) + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + @After + public void tearDown() { + verify(titanDao).commit(); + } + + @Test + public void getPolicyProperties_userIdIsNull() { + String userId = null; + ResponseFormat forbiddenResponse = new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()); + when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenReturn(Either.right(forbiddenResponse)); + Either, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null); + assertThat(policyProperties.right().value()).isSameAs(forbiddenResponse); + } + + @Test + public void getPolicyProperties_componentNotFound() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse); + Either, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.right().value()).isSameAs(notFoundResponse); + } + + @Test + public void getPolicyProperties_policyNotExist() { + doPolicyValidations(); + ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, "nonExistingPolicy", RESOURCE_ID)).thenReturn(notFoundResponse); + Either, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, "nonExistingPolicy", USER_ID); + assertThat(policyProperties.right().value()).isEqualTo(notFoundResponse); + } + + @Test + public void getPolicyProperties_noPropertiesOnPolicy() { + doPolicyValidations(); + Either, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, NO_PROPS_POLICY, USER_ID); + assertThat(policyProperties.left().value()).isNull(); + } + + @Test + public void getPolicyProperties() { + doPolicyValidations(); + Either, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID); + assertThat(policyProperties.left().value()) + .usingElementComparatorOnFields("uniqueId") + .containsExactly(prop1, prop2); + } + + private void doPolicyValidations() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User())); + ArgumentCaptor filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class); + when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.left(resource)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java new file mode 100644 index 0000000000..7dc12d96e6 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java @@ -0,0 +1,110 @@ +package org.openecomp.sdc.be.components.impl; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static com.google.common.collect.Sets.newHashSet; +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTypeBusinessLogicTest { + + private static final String USER_ID = "userId"; + private static final Set EXCLUDED_POLICY_TYPES = newHashSet("type1", "type2"); + private static final String COMPONENT_TYPE = "VF"; + + @InjectMocks + private PolicyTypeBusinessLogic testInstance; + @Mock + private TitanDao titanDao; + @Mock + private PolicyTypeOperation policyTypeOperation; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private UserValidations userValidations; + + @Before + public void setUp() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.left(new User())); + when(componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(any(StorageOperationStatus.class))).thenCallRealMethod(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES)); + } + + @BeforeClass + public static void beforeClass() { + new DummyConfigurationManager(); + } + + @Test + public void getAllPolicyTypes_userNotExist() { + ResponseFormat userNotExistResponse = new ResponseFormat(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.right(userNotExistResponse)); + Either, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(userNotExistResponse); + } + + @Test + public void getAllPolicyTypes_whenExcludePolicyTypesSetIsNull_passNullExcludedTypesSet() { + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenCallRealMethod(); + when(policyTypeOperation.getAllPolicyTypes(null)).thenReturn(Either.left(emptyList())); + Either, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + } + + @Test + public void getAllPolicyTypes() { + List policyTypes = Arrays.asList(new PolicyTypeBuilder().setUniqueId("id1").build(), + new PolicyTypeBuilder().setUniqueId("id2").build(), + new PolicyTypeBuilder().setUniqueId("id3").build()); + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.left(policyTypes)); + Either, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isSameAs(policyTypes); + } + + @Test + public void getAllPolicyTypes_noPolicyTypes() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.left().value()).isEmpty(); + verify(titanDao).commit(); + } + + @Test + public void getAllPolicyTypes_err() { + when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + ResponseFormat errResponse = new ResponseFormat(); + when(componentsUtils.getResponseFormat(StorageOperationStatus.GENERAL_ERROR)).thenReturn(errResponse); + Either, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE); + assertThat(allPolicyTypes.right().value()).isSameAs(errResponse); + verify(titanDao).commit(); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index f7724aaeff..8054baf15f 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -20,22 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Ignore; @@ -44,13 +29,13 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; +import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; @@ -98,1635 +83,1738 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class ResourceBusinessLogicTest { - private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName()); - public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; - public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; - public static final String RESOURCE_SUBCATEGORY = "Router"; + private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class); + public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router"; + public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; + public static final String RESOURCE_SUBCATEGORY = "Router"; - public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; - public static final String UPDATED_SUBCATEGORY = "Gateway"; + public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway"; + public static final String UPDATED_SUBCATEGORY = "Gateway"; - public static final String RESOURCE_NAME = "My-Resource_Name with space"; + public static final String RESOURCE_NAME = "My-Resource_Name with space"; private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF"; + private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR"; private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC"; private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF"; - - final ServletContext servletContext = Mockito.mock(ServletContext.class); - IAuditingManager iAuditingManager = null; - IElementOperation mockElementDao; - TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); - NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); - TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); - final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); - final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); - final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); - final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - ResponseFormatManager responseManager = null; - AuditingManager auditingManager = Mockito.mock(AuditingManager.class); - GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - User user = null; - Resource resourceResponse = null; - Resource genericVF = null; - Resource genericVFC = null; - Resource genericPNF = null; - ComponentsUtils componentsUtils = new ComponentsUtils(); - ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); - CsarOperation csarOperation = Mockito.mock(CsarOperation.class); - Map emptyDataTypes = new HashMap(); - private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); - CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); - - - public ResourceBusinessLogicTest() { - - } - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - Mockito.reset(propertyOperation); - - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // Elements - mockElementDao = new ElementOperationMock(); - - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - - Either eitherCountRoot = Either.left(1); - Either eitherFalse = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); - - Either eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); - - Either eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); - - Either validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either validateDerivedNotExists = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); - when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - - // createResource - resourceResponse = createResourceObject(true); - Either eitherCreate = Either.left(resourceResponse); - Either eitherValidate = Either.left(null); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); - Map emptyDataTypes = new HashMap(); - when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - - // BL object - artifactManager.nodeTemplateOperation = nodeTemplateOperation; - bl = new ResourceBusinessLogic(); - bl.setElementDao(mockElementDao); - bl.setUserAdmin(mockUserAdmin); - bl.setCapabilityTypeOperation(capabilityTypeOperation); - componentsUtils.Init(); - componentsUtils.setAuditingManager(auditingManager); - bl.setComponentsUtils(componentsUtils); - bl.setLifecycleManager(lifecycleBl); - bl.setGraphLockOperation(graphLockOperation); - bl.setArtifactsManager(artifactManager); - bl.setPropertyOperation(propertyOperation); - bl.setTitanGenericDao(mockTitanDao); - bl.setApplicationDataTypeCache(applicationDataTypeCache); - bl.setCsarOperation(csarOperation); - bl.setCacheManagerOperation(cacheManager); - bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); - toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); - toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); - bl.setToscaOperationFacade(toscaOperationFacade); - Resource resourceCsar = createResourceObjectCsar(true); - setCanWorkOnResource(resourceCsar); - Either oldResourceRes = Either.left(resourceCsar); - when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); - responseManager = ResponseFormatManager.getInstance(); - - } - - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource createResourceObjectCsar(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setResourceVendorModelNumber(""); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - resource.setCsarUUID("valid_vf.csar"); - resource.setCsarVersion("1"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; - } - - private Resource setCanWorkOnResource(Resource resource) { - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setLastUpdaterUserId(user.getUserId()); - return resource; - } - - @Test - public void testHappyScenario() { - Resource resource = createResourceObject(false); - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - assertEquals(createResourceObject(true), createResponse.left().value()); - } - - @Test - public void testUpdateHappyScenario() { - Resource resource = createResourceObjectCsar(true); - setCanWorkOnResource(resource); - - Either resourceLinkedToCsarRes = Either.left(resource); - when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); - Either validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); - if (updateResponse.isRight()) { - assertEquals(new Integer(200), updateResponse.right().value().getStatus()); - } - assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); - } - - /* CREATE validations - start ***********************/ - // Resource name - start - - @Test - public void testFailedResourceValidations() { - testResourceNameExist(); - testResourceNameEmpty(); - // testResourceNameExceedsLimit(); - testResourceNameWrongFormat(); - testResourceDescExceedsLimitCreate(); - testResourceDescNotEnglish(); - testResourceDescriptionEmpty(); - testResourceDescriptionMissing(); - testResourceIconMissing(); - testResourceIconInvalid(); - testResourceIconExceedsLimit(); - testResourceTagNotExist(); - testResourceTagEmpty(); - testTagsExceedsLimitCreate(); - testTagsNoServiceName(); - testInvalidTag(); - - testContactIdTooLong(); - testContactIdWrongFormatCreate(); - testResourceContactIdEmpty(); - testResourceContactIdMissing(); - testVendorNameExceedsLimit(); - testVendorNameWrongFormatCreate(); - testVendorReleaseWrongFormat(); - testVendorReleaseExceedsLimitCreate(); - testResourceVendorModelNumberExceedsLimit(); - testResourceVendorNameMissing(); - testResourceVendorReleaseMissing(); - testResourceCategoryExist(); - testResourceBadCategoryCreate(); - testHappyScenarioCostLicenseType(); - testCostWrongFormatCreate(); - testLicenseTypeWrongFormatCreate(); - testResourceTemplateNotExist(); - testResourceTemplateEmpty(); - testResourceTemplateInvalid(); - } - - private void testResourceNameExist() { - String resourceName = "alreadyExists"; - Resource resourceExist = createResourceObject(false); - resourceExist.setName(resourceName); - resourceExist.getTags().add(resourceName); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - private void testResourceNameEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setName(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceNameExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - resourceExccedsNameLimit.setName(tooLongResourceName); - - Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - private void testResourceNameWrongFormat() { - Resource resource = createResourceObject(false); - // contains : - String nameWrongFormat = "ljg?fd"; - resource.setName(nameWrongFormat); - - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Resource name - end - // Resource description - start - private void testResourceDescExceedsLimitCreate() { - Resource resourceExccedsDescLimit = createResourceObject(false); - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - - resourceExccedsDescLimit.setDescription(tooLongResourceDesc); - - Either createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - } - - private void testResourceDescNotEnglish() { - Resource notEnglish = createResourceObject(false); - // Not english - String notEnglishDesc = "\uC2B5"; - notEnglish.setDescription(notEnglishDesc); - - Either createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(""); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceDescriptionMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDescription(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); - } - // Resource description - end - // Resource icon start - - private void testResourceIconMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconInvalid() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("kjk3453^&"); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceIconExceedsLimit() { - Resource resourceExist = createResourceObject(false); - resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); - } - - // Resource icon end - // Resource tags - start - private void testResourceTagNotExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testResourceTagEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setTags(new ArrayList()); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); - } - - private void testTagsExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List tagsList = new ArrayList(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resourceExccedsNameLimit.getName()); - - resourceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - - } - - private void testTagsSingleExceedsLimit() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; - String tag2 = resourceExccedsNameLimit.getName(); - List tagsList = new ArrayList(); - tagsList.add(tag1); - tagsList.add(tag2); - - resourceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); - - } - - private void testTagsNoServiceName() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb"; - List tagsList = new ArrayList(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); - - } - - private void testInvalidTag() { - Resource serviceExccedsNameLimit = createResourceObject(false); - String tag1 = "afzs2qLBb%#%"; - List tagsList = new ArrayList(); - tagsList.add(tag1); - serviceExccedsNameLimit.setTags(tagsList); - - Either createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" }); - - } - - // Resource tags - stop - // Resource contact start - - private void testContactIdTooLong() { - Resource resourceContactId = createResourceObject(false); - // 59 chars instead of 50 - String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; - resourceContactId.setContactId(contactIdTooLong); - - Either createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testContactIdWrongFormatCreate() { - Resource resourceContactId = createResourceObject(false); - // 3 letters and 3 digits and special characters - String contactIdFormatWrong = "yrt134!!!"; - resourceContactId.setContactId(contactIdFormatWrong); - - Either createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(""); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceContactIdMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setContactId(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testVendorNameExceedsLimit() { - Resource resourceExccedsVendorNameLimit = createResourceObject(false); - String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); - - Either createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); - } - - private void testResourceVendorModelNumberExceedsLimit() { - Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); - String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); - - Either createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); - } - - private void testVendorNameWrongFormatCreate() { - Resource resource = createResourceObject(false); - // contains * - String nameWrongFormat = "ljg*fd"; - resource.setVendorName(nameWrongFormat); - - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - } - - private void testVendorReleaseWrongFormat() { - Resource resource = createResourceObject(false); - // contains > - String nameWrongFormat = "1>2"; - resource.setVendorRelease(nameWrongFormat); - - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); - - } - - private void testVendorReleaseExceedsLimitCreate() { - Resource resourceExccedsNameLimit = createResourceObject(false); - String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; - resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); - - Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - private void testResourceVendorNameMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorName(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); - } - - private void testResourceVendorReleaseMissing() { - Resource resourceExist = createResourceObject(false); - resourceExist.setVendorRelease(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); - } - - // Resource vendor name/release stop - // Category start - private void testResourceCategoryExist() { - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - private void testResourceBadCategoryCreate() { - - Resource resourceExist = createResourceObject(false); - resourceExist.setCategories(null); - resourceExist.addCategory("koko", "koko"); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - // Category stop - // Cost start - private void testHappyScenarioCostLicenseType() { - Resource createResourceObject = createResourceObject(false); - Resource createResourceObjectAfterCreate = createResourceObject(true); - // Adding cost and licenseType to basic mock - Either eitherCreate = Either.left(createResourceObjectAfterCreate); - when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate); - - String cost = "123.456"; - String licenseType = "User"; - createResourceObject.setCost(cost); - createResourceObject.setLicenseType(licenseType); - Either createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - if (createResponse.isRight()) { - assertEquals(new Integer(200), createResponse.right().value().getStatus()); - } - createResourceObjectAfterCreate.setCost(cost); - createResourceObjectAfterCreate.setLicenseType(licenseType); - assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); - } - - private void testCostWrongFormatCreate() { - Resource resourceCost = createResourceObject(false); - // Comma instead of fullstop - String cost = "12356,464"; - resourceCost.setCost(cost); - - Either createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // Cost stop - // License type start - private void testLicenseTypeWrongFormatCreate() { - Resource resourceLicenseType = createResourceObject(false); - // lowcase - String licenseType = "cpu"; - resourceLicenseType.setLicenseType(licenseType); - - Either createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_CONTENT); - } - - // License type stop - // Derived from start - private void testResourceTemplateNotExist() { - Resource resourceExist = createResourceObject(false); - List list = null; - resourceExist.setDerivedFrom(list); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateEmpty() { - Resource resourceExist = createResourceObject(false); - resourceExist.setDerivedFrom(new ArrayList()); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - private void testResourceTemplateInvalid() { - Resource resourceExist = createResourceObject(false); - ArrayList derivedFrom = new ArrayList(); - derivedFrom.add("kuku"); - resourceExist.setDerivedFrom(derivedFrom); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - // Derived from stop - - private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); - assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); - } - - // UPDATE tests - start - // Resource name - @Test - public void testResourceNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setName(nameWrongFormat); - - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testResourceNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String name = "ljg"; - updatedResource.setName(name); - resource.setVersion("1.0"); - - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); - - } - - @Ignore - public void testResourceNameExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 51 chars, the limit is 50 - String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; - updatedResource.setName(tooLongResourceName); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); - } - - @Test - public void testResourceNameAlreadyExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceName = "alreadyExists"; - updatedResource.setName(resourceName); - Either dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); - } - - // - - @Test - public void testResourceDescExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // 1025 chars, the limit is 1024 - String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" - + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" - + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" - + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" - + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" - + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" - + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" - + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; - updatedResource.setDescription(tooLongResourceDesc); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); - - } - - @Test - public void testIconWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains . - String icon = "icon.jpg"; - updatedResource.setIcon(icon); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); - - } - - @Test - public void testIconAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains - String icon = "icon"; - updatedResource.setIcon(icon); - - resource.setVersion("1.0"); - ; - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); - - } - - @Test - public void testTagsExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; - String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; - String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; - String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; - String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; - String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; - String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; - String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; - String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; - String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; - String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; - String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; - String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; - String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; - String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; - String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; - String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; - String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; - String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; - - List tagsList = new ArrayList(); - tagsList.add(tag1); - tagsList.add(tag2); - tagsList.add(tag3); - tagsList.add(tag4); - tagsList.add(tag5); - tagsList.add(tag6); - tagsList.add(tag7); - tagsList.add(tag8); - tagsList.add(tag9); - tagsList.add(tag10); - tagsList.add(tag11); - tagsList.add(tag12); - tagsList.add(tag13); - tagsList.add(tag14); - tagsList.add(tag15); - tagsList.add(tag16); - tagsList.add(tag17); - tagsList.add(tag18); - tagsList.add(tag19); - tagsList.add(tag20); - tagsList.add(tag21); - tagsList.add(resource.getName()); - - updatedResource.setTags(tagsList); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); - } - - @Test - public void testVendorNameWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); - - } - - @Test - public void testVendorNameAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - // contains * - String nameWrongFormat = "ljg*fd"; - updatedResource.setVendorName(nameWrongFormat); - resource.setVersion("1.0"); - ; - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED); - - } - - @Test - public void testVendorReleaseExceedsLimit_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - // 129 chars, the limit is 128 - String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; - updatedResource.setVendorRelease(tooLongVendorRelease); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); - } - - @Ignore - public void testContactIdWrongFormat_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - // 3 letters and 3 digits - String contactIdTooLong = "yrt134"; - updatedResource.setContactId(contactIdTooLong); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceBadCategory_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - String badCategory = "ddfds"; - updatedResource.setCategories(null); - updatedResource.addCategory(badCategory, "fikt"); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); - } - - @Test - public void testResourceCategoryAfterCertify_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - String resourceId = resource.getUniqueId(); - updatedResource.setCategories(null); - updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); - resource.setVersion("1.0"); - ; - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); - } - - // Derived from start - @Test - public void testResourceTemplateNotExist_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - String resourceId = resource.getUniqueId(); - - List list = null; - updatedResource.setDerivedFrom(list); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateEmpty_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - updatedResource.setDerivedFrom(new ArrayList()); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); - } - - @Test - public void testResourceTemplateInvalid_UPDATE() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - ArrayList derivedFrom = new ArrayList(); - derivedFrom.add("kuku"); - updatedResource.setDerivedFrom(derivedFrom); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); - } - - @Test - public void testResourceTemplateCertify_UPDATE_HAPPY() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either isToscaNameExtending = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); - - Either, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); - when(propertyOperation.deleteAllPropertiesAssociatedToNode(Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); - - resource.setVersion("1.0"); - - ArrayList derivedFrom = new ArrayList(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either dataModelResponse = Either.left(updatedResource); - when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); - assertTrue(createResponse.isLeft()); - } - - @Test - public void testResourceTemplateCertify_UPDATE_SAD() { - Resource resource = createResourceObject(true); - Resource updatedResource = createResourceObject(true); - String resourceId = resource.getUniqueId(); - - // this is in order to prevent failing with 403 earlier - Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); - when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); - - Either isToscaNameExtending = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) - .thenReturn(isToscaNameExtending); - - resource.setVersion("1.0"); - - ArrayList derivedFrom = new ArrayList(); - derivedFrom.add("tosca.nodes.Root"); - updatedResource.setDerivedFrom(derivedFrom); - Either dataModelResponse = Either.left(resource); - when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); - Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, - false); - assertTrue(createResponse.isRight()); - - assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); - } - // Derived from stop - - @Test - public void createOrUpdateResourceAlreadyCheckout() { - Resource resourceExist = createResourceObject(false); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - createResponse.left().value().setLastUpdaterUserId(user.getUserId()); - assertTrue(createResponse.isLeft()); - - Either getLatestResult = Either.left(createResponse.left().value()); - Either getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - Resource resourceToUpdtae = createResourceObject(false); - - Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceCertified() { - Resource resourceExist = createResourceObject(false); - - Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - - assertTrue(createResponse.isLeft()); - Resource certifiedResource = createResponse.left().value(); - certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - certifiedResource.setVersion("1.0"); - - - Either getLatestResult = Either.left(certifiedResource); - Either getCompLatestResult = Either.left(createResponse.left().value()); - when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); - when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult); - - when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); - - Resource resourceToUpdtae = createResourceObject(false); - - Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void createOrUpdateResourceNotExist() { - Resource resourceToUpdtae = createResourceObject(false); - - Either getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); - - Either getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); - when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); - - Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); - assertTrue(createOrUpdateResource.isLeft()); - - Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class)); - Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); - - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { - Resource basic = createResourceObject(true); - - Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - - @Test - public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1"); - List properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); - when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); - Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isLeft()); - } - @Test - public void testValidatePropertiesDefaultValues_FailedWithProperties() { - Resource basic = createResourceObject(true); - PropertyDefinition property = new PropertyDefinition(); - property.setName("myProperty"); - property.setType(ToscaPropertyType.INTEGER.getType()); - property.setDefaultValue("1.5"); - List properties = new ArrayList<>(); - properties.add(property); - basic.setProperties(properties); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + IElementOperation mockElementDao; + TitanDao mockTitanDao = Mockito.mock(TitanDao.class); + UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); + NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); + TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); + final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class); + final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); + final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); + final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + UserValidations userValidations = Mockito.mock(UserValidations.class); + WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class); + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + ResponseFormatManager responseManager = null; + GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + User user = null; + Resource resourceResponse = null; + Resource genericVF = null; + Resource genericCR = null; + Resource genericVFC = null; + Resource genericPNF = null; + ComponentsUtils componentsUtils; + ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); + CsarOperation csarOperation = Mockito.mock(CsarOperation.class); + Map emptyDataTypes = new HashMap(); + private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class); + CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class); + + + public ResourceBusinessLogicTest() { + + } + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); + + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + + // Elements + mockElementDao = new ElementOperationMock(); + + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); + when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(Either.left(user)); + when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user)); + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); + + Either eitherCountRoot = Either.left(1); + Either eitherFalse = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); + + Either eitherCountExist = Either.left(true); + when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); + + Either eitherCount = Either.left(false); + when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount); + /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); + when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/ + + Either validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either validateDerivedNotExists = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); + + // createResource + resourceResponse = createResourceObject(true); + Either eitherCreate = Either.left(resourceResponse); + Either eitherValidate = Either.left(null); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate); + Map emptyDataTypes = new HashMap(); + when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); + + // BL object + artifactManager.setNodeTemplateOperation(nodeTemplateOperation); + bl = new ResourceBusinessLogic(); + bl.setElementDao(mockElementDao); + bl.setUserAdmin(mockUserAdmin); + bl.setCapabilityTypeOperation(capabilityTypeOperation); + bl.setComponentsUtils(componentsUtils); + bl.setLifecycleManager(lifecycleBl); + bl.setGraphLockOperation(graphLockOperation); + bl.setArtifactsManager(artifactManager); + bl.setPropertyOperation(propertyOperation); + bl.setTitanGenericDao(mockTitanDao); + bl.setApplicationDataTypeCache(applicationDataTypeCache); + bl.setCsarOperation(csarOperation); + bl.setCacheManagerOperation(cacheManager); + bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic); + toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); + toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setUserValidations(userValidations); + Resource resourceCsar = createResourceObjectCsar(true); + setCanWorkOnResource(resourceCsar); + Either oldResourceRes = Either.left(resourceCsar); + when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + responseManager = ResponseFormatManager.getInstance(); + + } + + private Resource createResourceObject(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource createResourceObjectCsar(boolean afterCreate) { + Resource resource = new Resource(); + resource.setName(RESOURCE_NAME); + resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + tgs.add(resource.getName()); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setResourceVendorModelNumber(""); + resource.setContactId("ya5467"); + resource.setIcon("MyIcon"); + resource.setCsarUUID("valid_vf.csar"); + resource.setCsarVersion("1"); + + if (afterCreate) { + resource.setName(resource.getName()); + resource.setVersion("0.1"); + + resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); + resource.setCreatorUserId(user.getUserId()); + resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + return resource; + } + + private Resource setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); + return resource; + } + + @Test + public void testHappyScenario() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createResourceObject(false); + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + assertEquals(createResourceObject(true), createResponse.left().value()); + } + + @Test + public void testUpdateHappyScenario() { + Resource resource = createResourceObjectCsar(true); + setCanWorkOnResource(resource); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either resourceLinkedToCsarRes = Either.left(resource); + when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes); + Either validateDerivedExists = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); + + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()); + if (updateResponse.isRight()) { + assertEquals(new Integer(200), updateResponse.right().value().getStatus()); + } + assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId()); + } + + /* CREATE validations - start ***********************/ + // Resource name - start + + @Test + public void testFailedResourceValidations() { + testResourceNameExist(); + testResourceNameEmpty(); + // testResourceNameExceedsLimit(); + testResourceNameWrongFormat(); + testResourceDescExceedsLimitCreate(); + testResourceDescNotEnglish(); + testResourceDescriptionEmpty(); + testResourceDescriptionMissing(); + testResourceIconMissing(); + testResourceIconInvalid(); + testResourceIconExceedsLimit(); + testResourceTagNotExist(); + testResourceTagEmpty(); + testTagsExceedsLimitCreate(); + testTagsNoServiceName(); + testInvalidTag(); + + testContactIdTooLong(); + testContactIdWrongFormatCreate(); + testResourceContactIdEmpty(); + testResourceContactIdMissing(); + testVendorNameExceedsLimit(); + testVendorNameWrongFormatCreate(); + testVendorReleaseWrongFormat(); + testVendorReleaseExceedsLimitCreate(); + testResourceVendorModelNumberExceedsLimit(); + testResourceVendorNameMissing(); + testResourceVendorReleaseMissing(); + testResourceCategoryExist(); + testResourceBadCategoryCreate(); + testHappyScenarioCostLicenseType(); + testCostWrongFormatCreate(); + testLicenseTypeWrongFormatCreate(); + testResourceTemplateNotExist(); + testResourceTemplateEmpty(); + testResourceTemplateInvalid(); + } + + private void testResourceNameExist() { + String resourceName = "alreadyExists"; + Resource resourceExist = createResourceObject(false); + resourceExist.setName(resourceName); + resourceExist.getTags().add(resourceName); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + private void testResourceNameEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setName(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceNameExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + resourceExccedsNameLimit.setName(tooLongResourceName); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + private void testResourceNameWrongFormat() { + Resource resource = createResourceObject(false); + // contains : + String nameWrongFormat = "ljg?fd"; + resource.setName(nameWrongFormat); + + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Resource name - end + // Resource description - start + private void testResourceDescExceedsLimitCreate() { + Resource resourceExccedsDescLimit = createResourceObject(false); + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + + resourceExccedsDescLimit.setDescription(tooLongResourceDesc); + + Either createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + } + + private void testResourceDescNotEnglish() { + Resource notEnglish = createResourceObject(false); + // Not english + String notEnglishDesc = "\uC2B5"; + notEnglish.setDescription(notEnglishDesc); + + Either createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(""); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceDescriptionMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDescription(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); + } + // Resource description - end + // Resource icon start + + private void testResourceIconMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconInvalid() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("kjk3453^&"); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceIconExceedsLimit() { + Resource resourceExist = createResourceObject(false); + resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf"); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH); + } + + // Resource icon end + // Resource tags - start + private void testResourceTagNotExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testResourceTagEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setTags(new ArrayList()); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS); + } + + private void testTagsExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resourceExccedsNameLimit.getName()); + + resourceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + + } + + private void testTagsSingleExceedsLimit() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI"; + String tag2 = resourceExccedsNameLimit.getName(); + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + + resourceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH); + + } + + private void testTagsNoServiceName() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME); + + } + + private void testInvalidTag() { + Resource serviceExccedsNameLimit = createResourceObject(false); + String tag1 = "afzs2qLBb%#%"; + List tagsList = new ArrayList(); + tagsList.add(tag1); + serviceExccedsNameLimit.setTags(tagsList); + + Either createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"}); + + } + + // Resource tags - stop + // Resource contact start + + private void testContactIdTooLong() { + Resource resourceContactId = createResourceObject(false); + // 59 chars instead of 50 + String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId"; + resourceContactId.setContactId(contactIdTooLong); + + Either createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testContactIdWrongFormatCreate() { + Resource resourceContactId = createResourceObject(false); + // 3 letters and 3 digits and special characters + String contactIdFormatWrong = "yrt134!!!"; + resourceContactId.setContactId(contactIdFormatWrong); + + Either createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(""); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceContactIdMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setContactId(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testVendorNameExceedsLimit() { + Resource resourceExccedsVendorNameLimit = createResourceObject(false); + String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName); + + Either createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH); + } + + private void testResourceVendorModelNumberExceedsLimit() { + Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false); + String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber); + + Either createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH); + } + + private void testVendorNameWrongFormatCreate() { + Resource resource = createResourceObject(false); + // contains * + String nameWrongFormat = "ljg*fd"; + resource.setVendorName(nameWrongFormat); + + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + } + + private void testVendorReleaseWrongFormat() { + Resource resource = createResourceObject(false); + // contains > + String nameWrongFormat = "1>2"; + resource.setVendorRelease(nameWrongFormat); + + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE); + + } + + private void testVendorReleaseExceedsLimitCreate() { + Resource resourceExccedsNameLimit = createResourceObject(false); + String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E"; + resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease); + + Either createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + private void testResourceVendorNameMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorName(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME); + } + + private void testResourceVendorReleaseMissing() { + Resource resourceExist = createResourceObject(false); + resourceExist.setVendorRelease(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE); + } + + // Resource vendor name/release stop + // Category start + private void testResourceCategoryExist() { + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + private void testResourceBadCategoryCreate() { + + Resource resourceExist = createResourceObject(false); + resourceExist.setCategories(null); + resourceExist.addCategory("koko", "koko"); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + // Category stop + // Cost start + private void testHappyScenarioCostLicenseType() { + Resource createResourceObject = createResourceObject(false); + Resource createResourceObjectAfterCreate = createResourceObject(true); + // Adding cost and licenseType to basic mock + Either eitherCreate = Either.left(createResourceObjectAfterCreate); + when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); + + String cost = "123.456"; + String licenseType = "User"; + createResourceObject.setCost(cost); + createResourceObject.setLicenseType(licenseType); + Either createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + if (createResponse.isRight()) { + assertEquals(new Integer(200), createResponse.right().value().getStatus()); + } + createResourceObjectAfterCreate.setCost(cost); + createResourceObjectAfterCreate.setLicenseType(licenseType); + assertEquals(createResourceObjectAfterCreate, createResponse.left().value()); + } + + private void testCostWrongFormatCreate() { + Resource resourceCost = createResourceObject(false); + // Comma instead of fullstop + String cost = "12356,464"; + resourceCost.setCost(cost); + + Either createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // Cost stop + // License type start + private void testLicenseTypeWrongFormatCreate() { + Resource resourceLicenseType = createResourceObject(false); + // lowcase + String licenseType = "cpu"; + resourceLicenseType.setLicenseType(licenseType); + + Either createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_CONTENT); + } + + // License type stop + // Derived from start + private void testResourceTemplateNotExist() { + Resource resourceExist = createResourceObject(false); + List list = null; + resourceExist.setDerivedFrom(list); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateEmpty() { + Resource resourceExist = createResourceObject(false); + resourceExist.setDerivedFrom(new ArrayList()); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + private void testResourceTemplateInvalid() { + Resource resourceExist = createResourceObject(false); + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("kuku"); + resourceExist.setDerivedFrom(derivedFrom); + + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + // Derived from stop + + private void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + assertEquals(expectedResponse.getStatus(), actualResponse.getStatus()); + assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage()); + } + + // UPDATE tests - start + // Resource name + @Test + public void testResourceNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setName(nameWrongFormat); + + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testResourceNameAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String name = "ljg"; + updatedResource.setName(name); + resource.setVersion("1.0"); + + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED); + + } + + @Ignore + public void testResourceNameExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 51 chars, the limit is 50 + String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK"; + updatedResource.setName(tooLongResourceName); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH); + } + + @Test + public void testResourceNameAlreadyExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceName = "alreadyExists"; + updatedResource.setName(resourceName); + Either dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName); + } + + // + + @Test + public void testResourceDescExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // 1025 chars, the limit is 1024 + String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP" + + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P" + + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk" + + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1" + + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe" + + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2" + + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4" + + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs"; + updatedResource.setDescription(tooLongResourceDesc); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH); + + } + + @Test + public void testIconWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains . + String icon = "icon.jpg"; + updatedResource.setIcon(icon); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); + + } + + @Test + public void testIconAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains + String icon = "icon"; + updatedResource.setIcon(icon); + + resource.setVersion("1.0"); + ; + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED); + + } + + @Test + public void testTagsExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ"; + String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW"; + String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE"; + String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb"; + String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr"; + String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd"; + String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf"; + String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg"; + String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh"; + String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj"; + String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk"; + String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs"; + String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz"; + String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx"; + String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2"; + String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3"; + String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4"; + String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5"; + String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0"; + + List tagsList = new ArrayList(); + tagsList.add(tag1); + tagsList.add(tag2); + tagsList.add(tag3); + tagsList.add(tag4); + tagsList.add(tag5); + tagsList.add(tag6); + tagsList.add(tag7); + tagsList.add(tag8); + tagsList.add(tag9); + tagsList.add(tag10); + tagsList.add(tag11); + tagsList.add(tag12); + tagsList.add(tag13); + tagsList.add(tag14); + tagsList.add(tag15); + tagsList.add(tag16); + tagsList.add(tag17); + tagsList.add(tag18); + tagsList.add(tag19); + tagsList.add(tag20); + tagsList.add(tag21); + tagsList.add(resource.getName()); + + updatedResource.setTags(tagsList); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH); + } + + @Test + public void testVendorNameWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorNameWrongFormat() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + // contains * + String nameWrongFormat = "ljg*fd"; + updatedResource.setVendorName(nameWrongFormat); + resource.setVersion("1.0"); + ; + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME); + + } + + @Test + public void testVendorReleaseExceedsLimit_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + // 129 chars, the limit is 128 + String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy"; + updatedResource.setVendorRelease(tooLongVendorRelease); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH); + } + + @Ignore + public void testContactIdWrongFormat_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + // 3 letters and 3 digits + String contactIdTooLong = "yrt134"; + updatedResource.setContactId(contactIdTooLong); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceBadCategory_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + String badCategory = "ddfds"; + updatedResource.setCategories(null); + updatedResource.addCategory(badCategory, "fikt"); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); + } + + @Test + public void testResourceCategoryAfterCertify_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + String resourceId = resource.getUniqueId(); + updatedResource.setCategories(null); + updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY); + resource.setVersion("1.0"); + ; + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED); + } + + // Derived from start + @Test + public void testResourceTemplateNotExist_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + String resourceId = resource.getUniqueId(); + + List list = null; + updatedResource.setDerivedFrom(list); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateEmpty_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + updatedResource.setDerivedFrom(new ArrayList()); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE); + } + + @Test + public void testResourceTemplateInvalid_UPDATE() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("kuku"); + updatedResource.setDerivedFrom(derivedFrom); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND); + } + + @Test + public void testResourceTemplateCertify_UPDATE_HAPPY() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either isToscaNameExtending = Either.left(true); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending); + + Either, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>()); + when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode); + + resource.setVersion("1.0"); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either dataModelResponse = Either.left(updatedResource); + when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false); + assertTrue(createResponse.isLeft()); + } + + @Test + public void testResourceTemplateCertify_UPDATE_SAD() { + Resource resource = createResourceObject(true); + Resource updatedResource = createResourceObject(true); + String resourceId = resource.getUniqueId(); + + // this is in order to prevent failing with 403 earlier + Either eitherUpdate = Either.left(setCanWorkOnResource(resource)); + when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate); + + Either isToscaNameExtending = Either.left(false); + when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())) + .thenReturn(isToscaNameExtending); + + resource.setVersion("1.0"); + + ArrayList derivedFrom = new ArrayList(); + derivedFrom.add("tosca.nodes.Root"); + updatedResource.setDerivedFrom(derivedFrom); + Either dataModelResponse = Either.left(resource); + when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse); + Either createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, + false); + assertTrue(createResponse.isRight()); + + assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND); + } + // Derived from stop + + @Test + public void createOrUpdateResourceAlreadyCheckout() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + createResponse.left().value().setLastUpdaterUserId(user.getUserId()); + assertTrue(createResponse.isLeft()); + + Either getLatestResult = Either.left(createResponse.left().value()); + Either getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + Resource resourceToUpdtae = createResourceObject(false); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceCertified() { + Resource resourceExist = createResourceObject(false); + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Either createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + + assertTrue(createResponse.isLeft()); + Resource certifiedResource = createResponse.left().value(); + certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + certifiedResource.setVersion("1.0"); + + + Either getLatestResult = Either.left(certifiedResource); + Either getCompLatestResult = Either.left(createResponse.left().value()); + when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult); + when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult); + + when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse); + + Resource resourceToUpdtae = createResourceObject(false); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void createOrUpdateResourceNotExist() { + Resource resourceToUpdtae = createResourceObject(false); + + Either getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult); + + Either getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult); + + Either, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false); + assertTrue(createOrUpdateResource.isLeft()); + + Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class)); + Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()); + + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() { + Resource basic = createResourceObject(true); + + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1"); + List properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); + when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true); + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isLeft()); + } + + @Test + public void testValidatePropertiesDefaultValues_FailedWithProperties() { + Resource basic = createResourceObject(true); + PropertyDefinition property = new PropertyDefinition(); + property.setName("myProperty"); + property.setType(ToscaPropertyType.INTEGER.getType()); + property.setDefaultValue("1.5"); + List properties = new ArrayList<>(); + properties.add(property); + basic.setProperties(properties); - when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); - Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); - assertTrue(validatePropertiesDefaultValues.isRight()); - } - -// @Test -// public void testDeleteMarkedResourcesNoResources() { -// List ids = new ArrayList<>(); -// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); + when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false); + Either validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic); + assertTrue(validatePropertiesDefaultValues.isRight()); + } + +// @Test +// public void testDeleteMarkedResourcesNoResources() { +// List ids = new ArrayList<>(); +// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources); +// +// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// assertTrue(deleteMarkedResources.left().value().isEmpty()); // -// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// assertTrue(deleteMarkedResources.left().value().isEmpty()); +// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); // -// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList()); +// } // -// } +// @Test +// public void testDeleteMarkedResources() { +// List ids = new ArrayList(); +// String resourceInUse = "123"; +// ids.add(resourceInUse); +// String resourceFree = "456"; +// ids.add(resourceFree); +// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); +// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); // -// @Test -// public void testDeleteMarkedResources() { -// List ids = new ArrayList(); -// String resourceInUse = "123"; -// ids.add(resourceInUse); -// String resourceFree = "456"; -// ids.add(resourceFree); -// Either, StorageOperationStatus> eitherNoResources = Either.left(ids); -// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources); +// Either resourceInUseResponse = Either.left(true); +// Either resourceFreeResponse = Either.left(false); // -// Either resourceInUseResponse = Either.left(true); -// Either resourceFreeResponse = Either.left(false); +// List artifacts = new ArrayList(); +// Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); +// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); // -// List artifacts = new ArrayList(); -// Either, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts); -// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse); +// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); +// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); // -// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse); -// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse); +// Either eitherDelete = Either.left(new Resource()); +// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); // -// Either eitherDelete = Either.left(new Resource()); -// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete); +// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); +// List deletedComponents = new ArrayList<>(); +// deletedComponents.add(resourceFree); +// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); // -// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK); -// List deletedComponents = new ArrayList<>(); -// deletedComponents.add(resourceFree); -// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents)); -// -// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); -// assertTrue(deleteMarkedResources.isLeft()); -// List resourceIdList = deleteMarkedResources.left().value(); -// assertFalse(resourceIdList.isEmpty()); -// assertTrue(resourceIdList.contains(resourceFree)); -// assertFalse(resourceIdList.contains(resourceInUse)); +// Either, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents(); +// assertTrue(deleteMarkedResources.isLeft()); +// List resourceIdList = deleteMarkedResources.left().value(); +// assertFalse(resourceIdList.isEmpty()); +// assertTrue(resourceIdList.contains(resourceFree)); +// assertFalse(resourceIdList.contains(resourceInUse)); // -// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); -// } - - @SuppressWarnings("unchecked") - @Test - public void testFindVfCsarArtifactsToHandle() { - - Class targetClass = ResourceBusinessLogic.class; - String methodName = "findVfCsarArtifactsToHandle"; - Resource resource = new Resource(); - String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; - String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; - String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; - - String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; - String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; - String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; - - byte[] oldPayloadData = "oldPayloadData".getBytes(); - byte[] newPayloadData = "newPayloadData".getBytes(); - Map deploymentArtifacts =new HashMap<>(); - - ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); - deploymentArtifactToUpdate.setMandatory(false); - deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); - deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); - deploymentArtifactToUpdate.setPayload(oldPayloadData); - deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); - deploymentArtifactToDelete.setMandatory(false); - deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); - deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); - deploymentArtifactToDelete.setPayload(oldPayloadData); - deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); - - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); - deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); - deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); - - Map artifacts = new HashMap<>(); - - ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); - artifactToUpdate.setMandatory(false); - artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); - artifactToUpdate.setArtifactType("SNMP_POLL"); - artifactToUpdate.setPayload(oldPayloadData); - artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToDelete = new ArtifactDefinition(); - artifactToDelete.setMandatory(false); - artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); - artifactToDelete.setArtifactType("SNMP_TRAP"); - artifactToDelete.setPayload(oldPayloadData); - artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); - - ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); - - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()),artifactToUpdate); - artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()),artifactToDelete); - artifacts.put("ignore",artifactToIgnore); - - resource.setDeploymentArtifacts(deploymentArtifacts); - resource.setArtifacts(artifacts); - - List artifactPathAndNameList = new ArrayList<>(); - NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, deploymentArtifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, - ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactToUpdate.getArtifactName()); - - NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName); - - NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, - ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, - newPayloadData, artifactInfoToCreateFileName); - - artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); - artifactPathAndNameList.add(informationalArtifactInfoToUpdate); - artifactPathAndNameList.add(deploymentArtifactInfoToCreate); - artifactPathAndNameList.add(informationalArtifactInfoToCreate); - - Object[] argObjects = {resource, artifactPathAndNameList, user}; - Class[] argClasses = {Resource.class, List.class, User.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = - (Either>, ResponseFormat>) method.invoke(bl, argObjects); - assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); - EnumMap> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Update).size()==2); - assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2); - - } - catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testVFGeneratedInputs() { - - Resource resource = createVF(); - List inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); - } - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckout() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - // create a new generic version without properties - genericVF.setVersion("2.0"); - genericVF.setProperties(null); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - List currentInputs = resource.getInputs(); - //verify previous inputs ownerId fields exist - user may not delete generated inputs - assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update required and valid - assertTrue(upgradeToLatestGeneric.left().value()); - //verify version was upgraded - assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not deleted - assertTrue(8 == resource.getInputs().size()); - //verify inputs ownerId fields were removed - user may delete/edit inputs - assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - } - - - @Test - public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { - - //create a VF that is derived from generic version 1.0 - Resource resource = createVF(); - - //add an input to the VF - PropertyDefinition newProp = new PropertyDefinition(); - newProp.setType("integer"); - newProp.setName("newProp"); - resource.getInputs().add(new InputDefinition(newProp)); - - //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type - genericVF.setVersion("2.0"); - newProp.setType("string"); - genericVF.setProperties(new ArrayList()); - genericVF.getProperties().add(newProp); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); - String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); - assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); - Either upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); - //verify success - assertTrue(upgradeToLatestGeneric.isLeft()); - //verify update is invalid an void - assertFalse(upgradeToLatestGeneric.left().value()); - //verify version was not upgraded - assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); - //verify inputs were not removed - assertTrue(9 == resource.getInputs().size()); - //verify user defined input exists - assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); - assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); - } - - @Test - public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { - - Resource resource = createPNF(); - List inputs = resource.getInputs(); - assertTrue(8 == inputs.size()); - for(InputDefinition input : inputs){ - assertNotNull(input.getOwnerId()); - } - assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); - assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); - assertTrue(0 == resource.getArtifacts().size()); - } - - - private Resource createVF() { - - genericVF = setupGenericTypeMock(GENERIC_VF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.VF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - private Resource createPNF() { - - genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); - when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); - Resource resource = createResourceObject(true); - resource.setDerivedFrom(null); - resource.setResourceType(ResourceTypeEnum.PNF); - when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); - when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); - when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); - when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); - Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); - assertTrue(createResponse.isLeft()); - return createResponse.left().value(); - } - - - +// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts); +// } + + @SuppressWarnings("unchecked") + @Test + public void testFindVfCsarArtifactsToHandle() { + + Class targetClass = ResourceBusinessLogic.class; + String methodName = "findVfCsarArtifactsToHandle"; + Resource resource = new Resource(); + String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml"; + String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml"; + String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml"; + + String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml"; + String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml"; + String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml"; + String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml"; + + byte[] oldPayloadData = "oldPayloadData".getBytes(); + byte[] newPayloadData = "newPayloadData".getBytes(); + Map deploymentArtifacts = new HashMap<>(); + + ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition(); + deploymentArtifactToUpdate.setMandatory(false); + deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName); + deploymentArtifactToUpdate.setArtifactType("SNMP_POLL"); + deploymentArtifactToUpdate.setPayload(oldPayloadData); + deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition(); + deploymentArtifactToDelete.setMandatory(false); + deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName); + deploymentArtifactToDelete.setArtifactType("SNMP_TRAP"); + deploymentArtifactToDelete.setPayload(oldPayloadData); + deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition(); + + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate); + deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete); + deploymentArtifacts.put("ignore", deploymentArtifactToIgnore); + + Map artifacts = new HashMap<>(); + + ArtifactDefinition artifactToUpdate = new ArtifactDefinition(); + artifactToUpdate.setMandatory(false); + artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName); + artifactToUpdate.setArtifactType("SNMP_POLL"); + artifactToUpdate.setPayload(oldPayloadData); + artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + + ArtifactDefinition artifactToDelete = new ArtifactDefinition(); + artifactToDelete.setMandatory(false); + artifactToDelete.setArtifactName(artifactInfoToDeleteFileName); + artifactToDelete.setArtifactType("SNMP_TRAP"); + artifactToDelete.setPayload(oldPayloadData); + artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToDelete.setIsFromCsar(true); + + ArtifactDefinition artifactToNotDelete = new ArtifactDefinition(); + artifactToNotDelete.setMandatory(false); + artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName); + artifactToNotDelete.setArtifactType("SNMP_TRAP"); + artifactToNotDelete.setPayload(oldPayloadData); + artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData)); + artifactToNotDelete.setIsFromCsar(false); + + ArtifactDefinition artifactToIgnore = new ArtifactDefinition(); + + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete); + artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete); + artifacts.put("ignore", artifactToIgnore); + + resource.setDeploymentArtifacts(deploymentArtifacts); + resource.setArtifacts(artifacts); + + List artifactPathAndNameList = new ArrayList<>(); + NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), false); + + NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null, + ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT, + newPayloadData, artifactToUpdate.getArtifactName(), true); + + NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false); + + NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null, + ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL, + newPayloadData, artifactInfoToCreateFileName, false); + + artifactPathAndNameList.add(deploymentArtifactInfoToUpdate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdate); + artifactPathAndNameList.add(deploymentArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToCreate); + artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar); + artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar); + + Object[] argObjects = {resource, artifactPathAndNameList, user}; + Class[] argClasses = {Resource.class, List.class, User.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = + (Either>, ResponseFormat>) method.invoke(bl, argObjects); + assertTrue(findVfCsarArtifactsToHandleRes.isLeft()); + EnumMap> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value(); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size() == 4); + assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size() == 1); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testVFGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + List inputs = resource.getInputs(); + assertTrue(8 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion())); + } + + @Test + public void testCRGeneratedInputs() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createCR(); + List inputs = resource.getInputs(); + assertTrue(5 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericCR.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericCR.getVersion())); + } + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckout() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + //create a VF that is derived from generic version 1.0 + Resource resource = createVF(); + // create a new generic version without properties + genericVF.setVersion("2.0"); + genericVF.setProperties(null); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + List currentInputs = resource.getInputs(); + //verify previous inputs ownerId fields exist - user may not delete generated inputs + assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update required and valid + assertTrue(upgradeToLatestGeneric.left().value()); + //verify version was upgraded + assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not deleted + assertTrue(8 == resource.getInputs().size()); + //verify inputs ownerId fields were removed - user may delete/edit inputs + assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + } + + + @Test + public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() { + + //create a VF that is derived from generic version 1.0 + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createVF(); + + //add an input to the VF + PropertyDefinition newProp = new PropertyDefinition(); + newProp.setType("integer"); + newProp.setName("newProp"); + resource.getInputs().add(new InputDefinition(newProp)); + + //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type + genericVF.setVersion("2.0"); + newProp.setType("string"); + genericVF.setProperties(new ArrayList()); + genericVF.getProperties().add(newProp); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod(); + String currentDerivedFromVersion = resource.getDerivedFromGenericVersion(); + assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size()); + Either upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource); + //verify success + assertTrue(upgradeToLatestGeneric.isLeft()); + //verify update is invalid an void + assertFalse(upgradeToLatestGeneric.left().value()); + //verify version was not upgraded + assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion)); + //verify inputs were not removed + assertTrue(9 == resource.getInputs().size()); + //verify user defined input exists + assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size()); + assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer")); + } + + @Test + public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() { + validateUserRoles(Role.ADMIN, Role.DESIGNER); + Resource resource = createPNF(); + List inputs = resource.getInputs(); + assertTrue(3 == inputs.size()); + for (InputDefinition input : inputs) { + assertNotNull(input.getOwnerId()); + } + assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName())); + assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion())); + assertTrue(0 == resource.getArtifacts().size()); + } + + + private Resource createVF() { + + genericVF = setupGenericTypeMock(GENERIC_VF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.VF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Resource createCR() { + + genericCR = setupGenericTypeMock(GENERIC_CR_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.CR); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + private Resource createPNF() { + + genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME); + when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF)); + Resource resource = createResourceObject(true); + resource.setDerivedFrom(null); + resource.setResourceType(ResourceTypeEnum.PNF); + when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource)); + when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF)); + when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod(); + when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod(); + Either createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null); + assertTrue(createResponse.isLeft()); + return createResponse.left().value(); + } + + + private Map getGenericPropertiesByToscaName(String toscaName) { + HashMap PNFProps = new HashMap() {{ + put("nf_function", "string"); + put("nf_role", "string"); + put("nf_type", "string"); + }}; + + HashMap CRProps = new HashMap() {{ + putAll(PNFProps); + put("nf_naming_code", "string"); + put("nf_naming", "org.openecomp.datatypes.Naming"); + }}; + + HashMap VFProps = new HashMap() {{ + putAll(CRProps); + put("availability_zone_max_count", "integer"); + put("min_instances", "integer"); + put("max_instances", "integer"); + }}; + + if (toscaName.contains("PNF")) return PNFProps; + if (toscaName.contains("CR")) return CRProps; + if (toscaName.contains("VF")) return VFProps; + + return new HashMap<>(); + } + + private Resource setupGenericTypeMock(String toscaName) { - - Resource genericType = createResourceObject(true); - genericType.setVersion("1.0"); - genericType.setToscaResourceName(toscaName); - String[] propNames = {"nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count", "min_instances", "max_instances"}; - String[] propTypes = {"string", "string", "string", "string", "org.openecomp.datatypes.Naming", "integer", "integer", "integer"}; - List genericProps = new ArrayList<>(); - for(int i = 0; i < 8; ++i){ - PropertyDefinition prop = new PropertyDefinition(); - prop.setName(propNames[i]); - prop.setType(propTypes[i]); - genericProps.add(prop); - } - genericType.setProperties(genericProps); - return genericType; - } - - - + + Resource genericType = createResourceObject(true); + genericType.setVersion("1.0"); + genericType.setToscaResourceName(toscaName); + List genericProps = new ArrayList<>(); + Map genericPropsMap = getGenericPropertiesByToscaName(toscaName); + genericPropsMap.forEach((name, type) -> { + PropertyDefinition prop = new PropertyDefinition(); + prop.setName(name); + prop.setType(type); + genericProps.add(prop); + }); + + genericType.setProperties(genericProps); + return genericType; + } + + private void validateUserRoles(Role... roles) { + List listOfRoles = Stream.of(roles).collect(Collectors.toList()); + when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true)); + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java index 581adb28df..3abf711b91 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.components.impl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -53,6 +44,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ConfigurationSource; @@ -61,252 +53,259 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class ResourceInstanceBusinessLogicTest { - private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; - private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; - private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; - private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; - private static final String SERVICE_ID = "MyServiceId"; - private static final String HEAT_LABEL = "myHeat"; - private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; - private static final String USER_ID = "jh0003"; - private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); - - static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); - - @InjectMocks - static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic(); - - public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); - public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); -// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); - public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); - static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - - // @BeforeClass - public static void setup() { - - Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - Map placeHolderData = (Map) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); - - ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); - Map artifacts = new HashMap(); - artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); - Either, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); - - ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); - Map artifactsNoPayload = new HashMap(); - artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); - Either, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); - - ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); - Map artifactsNoParams = new HashMap(); - artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); - Either, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); - Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); - - Either eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); - Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); - - Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap(AuditingFieldsKeysEnum.class)); - - Either eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); - - Either eitherUser = Either.left(adminUser); - Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); - - Object lightService = new Service(); - Either eitherLightService = Either.left(lightService); -// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService); - - Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class), - Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class)); - - Either heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); - - Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), - Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); - - Either, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList()); - Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); - - bl.setToscaOperationFacade(toscaOperationFacade); - - StorageOperationStatus status = StorageOperationStatus.OK; - Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); - Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); - Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); - - } - - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); -// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); - setup(); - } - - @Test - public void testAddResourceInstanceArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - - Map existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); + private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId"; + private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload"; + private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams"; + private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId"; + private static final String SERVICE_ID = "MyServiceId"; + private static final String HEAT_LABEL = "myHeat"; + private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env"; + private static final String USER_ID = "jh0003"; + private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis(); + + static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null); + + @InjectMocks + static ComponentInstanceBusinessLogic bl = new ComponentInstanceBusinessLogic(); + + public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class); + public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class); +// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class); + public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + + static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"); + static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + + // @BeforeClass + public static void setup() { + + Map deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + Map placeHolderData = (Map) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME); + + ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true); + Map artifacts = new HashMap(); + artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact); + Either, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact); + + ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false); + Map artifactsNoPayload = new HashMap(); + artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload); + Either, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload); + + ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false); + Map artifactsNoParams = new HashMap(); + artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams); + Either, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams); + Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams); + + Either eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL)); + Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder); + + Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap(AuditingFieldsKeysEnum.class)); + + Either eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact); + + Either eitherUser = Either.left(adminUser); + Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser); + + Object lightService = new Service(); + Either eitherLightService = Either.left(lightService); + + Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.any(AuditingActionEnum.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ResourceAuditData.class)); + + Either heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false)); + + Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class), + Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither); + + Either, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList()); + Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft); + + bl.setToscaOperationFacade(toscaOperationFacade); + + StorageOperationStatus status = StorageOperationStatus.OK; + Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status); + Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status); + Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status); + + } + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); +// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager); + setup(); + } + + @Test + public void testAddResourceInstanceArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + + Map existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition); // -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); // -// List heatParameters = heatDefinition.getListHeatParameters(); -// assertNotNull(heatParameters); +// List heatParameters = heatDefinition.getListHeatParameters(); +// assertNotNull(heatParameters); // -// List heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNotNull(heatEnvParameters); +// List heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNotNull(heatEnvParameters); // -// assertEquals(heatParameters.size(), heatEnvParameters.size()); +// assertEquals(heatParameters.size(), heatEnvParameters.size()); // -// int index = 0; -// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { -// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); -// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); -// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); -// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); -// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); -// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); -// // current of heat parameter should be the default for heat env -// // parameter -// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); +// int index = 0; +// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) { +// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index); +// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId()); +// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType()); +// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName()); +// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription()); +// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue()); +// // current of heat parameter should be the default for heat env +// // parameter +// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue()); // -// index++; -// } - } - - @Test - public void testAddResourceInstanceArtifactsNoParams() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); -// assertTrue(deploymentArtifacts.size() == 2); - - ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); - assertNotNull(heatDefinition); -// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); - -// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); -// assertNotNull(heatEnvDefinition); - - List heatParameters = heatDefinition.getListHeatParameters(); - assertNull(heatParameters); - -// List heatEnvParameters = heatEnvDefinition.getListHeatParameters(); -// assertNull(heatEnvParameters); - - } - - @SuppressWarnings("unchecked") - @Test - public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { - ComponentInstance resourceInstance = new ComponentInstance(); - resourceInstance.setName(RESOURCE_INSTANCE_ID); - resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); - resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - Map existingEnvVersions = new HashMap<>(); - Resource originResource = new Resource(); - originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); - - Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); - assertTrue(addArtifactsRes.isLeft()); - - Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); - assertNotNull(deploymentArtifacts); - assertTrue(deploymentArtifacts.size() == 0); - - Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); - } - - private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { - ArtifactDefinition artifactInfo = new ArtifactDefinition(); - - artifactInfo.setArtifactName(artifactName + ".yml"); - artifactInfo.setArtifactType("HEAT"); - artifactInfo.setDescription("hdkfhskdfgh"); - artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - - artifactInfo.setUserIdCreator(userId); - String fullName = "Jim H"; - artifactInfo.setUpdaterFullName(fullName); - // long time = System.currentTimeMillis(); - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(userId); - artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); - artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); - - if (!placeholderOnly) { - artifactInfo.setEsId(artifactInfo.getUniqueId()); - artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); - - if (withHeatParams) { - List heatParams = new ArrayList(); - HeatParameterDefinition heatParam = new HeatParameterDefinition(); - heatParam.setCurrentValue("11"); - heatParam.setDefaultValue("22"); - heatParam.setDescription("desc"); - heatParam.setName("myParam"); - heatParam.setType("number"); - heatParams.add(heatParam); - artifactInfo.setListHeatParameters(heatParams); - } - } - - return artifactInfo; - } - - private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } +// index++; +// } + } + + @Test + public void testAddResourceInstanceArtifactsNoParams() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); +// assertTrue(deploymentArtifacts.size() == 2); + + ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase()); + assertNotNull(heatDefinition); +// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition); + +// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase()); +// assertNotNull(heatEnvDefinition); + + List heatParameters = heatDefinition.getListHeatParameters(); + assertNull(heatParameters); + +// List heatEnvParameters = heatEnvDefinition.getListHeatParameters(); +// assertNull(heatEnvParameters); + + } + + @SuppressWarnings("unchecked") + @Test + public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception { + ComponentInstance resourceInstance = new ComponentInstance(); + resourceInstance.setName(RESOURCE_INSTANCE_ID); + resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD); + resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID); + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + Map existingEnvVersions = new HashMap<>(); + Resource originResource = new Resource(); + originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD); + + Either addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions); + assertTrue(addArtifactsRes.isLeft()); + + Map deploymentArtifacts = resourceInstance.getDeploymentArtifacts(); + assertNotNull(deploymentArtifacts); + assertTrue(deploymentArtifacts.size() == 0); + + Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString()); + } + + private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) { + ArtifactDefinition artifactInfo = new ArtifactDefinition(); + + artifactInfo.setArtifactName(artifactName + ".yml"); + artifactInfo.setArtifactType("HEAT"); + artifactInfo.setDescription("hdkfhskdfgh"); + artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + + artifactInfo.setUserIdCreator(userId); + String fullName = "Jim H"; + artifactInfo.setUpdaterFullName(fullName); + // long time = System.currentTimeMillis(); + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(userId); + artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase()); + artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel())); + + if (!placeholderOnly) { + artifactInfo.setEsId(artifactInfo.getUniqueId()); + artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz"); + + if (withHeatParams) { + List heatParams = new ArrayList(); + HeatParameterDefinition heatParam = new HeatParameterDefinition(); + heatParam.setCurrentValue("11"); + heatParam.setDefaultValue("22"); + heatParam.setDescription("desc"); + heatParam.setName("myParam"); + heatParam.setType("number"); + heatParams.add(heatParam); + artifactInfo.setListHeatParameters(heatParams); + } + } + + return artifactInfo; + } + + private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java index 309689af45..5f4dfdc6f7 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java @@ -1,12 +1,6 @@ package org.openecomp.sdc.be.components.impl.generic; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +14,12 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class GenericTypeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java new file mode 100644 index 0000000000..6b1b37e5bc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java @@ -0,0 +1,258 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class PolicyTypeImportUtilsTest { + + private static final String UNIQUE_ID_EXSISTS = "uniqueId"; + + @Test + public void isPolicyTypesEquals_whenBothTypesAreNull_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, null)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenOneTypeIsNull_returnFalse() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(new PolicyTypeDefinition(), null)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, new PolicyTypeDefinition())).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTypesIsSameObject_returnTrue() { + PolicyTypeDefinition policyType = new PolicyTypeDefinition(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(policyType, policyType)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_allFieldsEquals_returnTrue() { + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(createPolicyTypeWithAllFields(), createPolicyTypeWithAllFields())).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenTypesAreDifferentInANonCompareFields_returnTrue() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setOwnerId("ownerIdNew"); + type2.setModificationTime(System.currentTimeMillis()); + type2.setCreationTime(System.currentTimeMillis()); + type2.setUniqueId("uniqueIdNew"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypesEquals_whenTypeIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setType("newType"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDescription("newDescription"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenTargetsAreDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setTargets(new ArrayList<>()); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenDerivedFromIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setDerivedFrom("newDerivedFrom"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenVersionIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setVersion("2.0"); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypesEquals_whenMetadataIsDifferent_returnFalse() { + PolicyTypeDefinition type1 = createPolicyTypeWithAllFields(); + PolicyTypeDefinition type2 = createPolicyTypeWithAllFields(); + type2.setMetadata(ImmutableMap.of("newKey", "newVal")); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() { + PolicyTypeDefinition noProperties = new PolicyTypeDefinition(); + PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build(); + PolicyTypeDefinition oneProp = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition twoProps = new PolicyTypeBuilder().setProperties(Arrays.asList(createPropertyDefinitionWithAllFields("prop1"), + createPropertyDefinitionWithAllFields("prop2"))) + .build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, oneProp)).isFalse(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(twoProps, oneProp)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesSamePropertiesList_returnTrue() { + List propList = Collections.singletonList(createPropertyDefinitionWithAllFields("prop1")); + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(propList).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(propList).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListFieldsEquals_returnTrue() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesListDifferentInANonComparedFields_returnTrue() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffNonComparedFields = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffNonComparedFields.setOwnerId("newOwner"); + prop1DiffNonComparedFields.setValue("newVal"); + prop1DiffNonComparedFields.setConstraints(null); + prop1DiffNonComparedFields.setUniqueId("newId"); + prop1DiffNonComparedFields.setHidden(true); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffNonComparedFields)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameName_returnFalse() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop2"))).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOFSameType_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1TypeInteger = createPropertyDefinitionWithAllFields("prop1"); + prop1TypeInteger.setType("integer"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1TypeInteger)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameDefaultVal_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDefault = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDefault.setDefaultValue("newDefVal"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDefault)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotOfSameSchema_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffSchema = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffSchema.setSchema(null); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffSchema)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsPasswordFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsPassword = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsPassword.setPassword(!prop1.isPassword()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsPassword)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesIsRequiredFieldNotSame_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffIsRequired = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffIsRequired.setRequired(!prop1.isRequired()); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsRequired)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + @Test + public void isPolicyTypeEquals_whenPropertiesNotSameDescription_returnFalse() { + PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1"); + PropertyDefinition prop1DiffDescription = createPropertyDefinitionWithAllFields("prop1"); + prop1DiffDescription.setDescription("newDescription"); + + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDescription)).build(); + assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse(); + } + + private PolicyTypeDefinition createPolicyTypeWithAllFields() { + return new PolicyTypeBuilder() + .setType("type1") + .setDerivedFrom("derivedFrom") + .setVersion("1.0") + .setDescription("description") + .setUniqueId("id1") + .setHighestVersion(true) + .setModificationTime(System.currentTimeMillis()) + .setCreationTime(System.currentTimeMillis()) + .setTargets(getTargets()) + .setOwner("owner") + .setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2")) + .build(); + } + + private PropertyDefinition createPropertyDefinitionWithAllFields(String name) { + return new PropertyDataDefinitionBuilder() + .setConstraints(Arrays.asList(new GreaterThanConstraint("abc"), new MinLengthConstraint(5))) + .setUniqueId("uid") + .setDefaultValue("val1") + .setType("string") + .setValue("val1") + .setName(name) + .setSchemaType("string") + .setOwnerId("owner") + .setStatus("status") + .setDescription("description") + .setIsPassword(false) + .setIsRequired(false) + .build(); + } + + private List getTargets() { + + return Collections.singletonList(UNIQUE_ID_EXSISTS); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java new file mode 100644 index 0000000000..0dac6ecb2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.be.components.impl.utils; + +import org.mockito.Mockito; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +public class TestGenerationUtils { + + public static ComponentsUtils getComponentsUtils() { + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + return new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java new file mode 100644 index 0000000000..fe6071239e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java @@ -0,0 +1,152 @@ +package org.openecomp.sdc.be.components.impl.version; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GroupMembersUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + private static final String INSTANCE_ID_PRE_CHANGE = "inst2"; + private static final String INSTANCE_ID_POST_CHANGE = "newInst2"; + @InjectMocks + private GroupMembersUpdateOperation testInstance; + @Mock + private GroupsOperation groupsOperation; + @Mock + private ComponentsUtils componentsUtils; + + @Captor + private ArgumentCaptor> updatedGroupsCaptor; + private GroupDefinition group1, group2, group3; + private Resource container; + private ComponentInstance prevInst2Version, currInst2Version; + private static final ComponentInstance DONT_CARE = new ComponentInstance(); + + @Before + public void setUp() throws Exception { + group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE); + group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3"); + group3 = createGroupWithMembers("group3", "inst1", "inst3"); + container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .setUniqueId(CONTAINER_ID) + .setComponentType(ComponentTypeEnum.RESOURCE) + .build(); + prevInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_PRE_CHANGE) + .build(); + currInst2Version = new ComponentInstanceBuilder() + .setId(INSTANCE_ID_POST_CHANGE) + .build(); + } + + @Test + public void whenNoGroupsOnContainer_returnOk() { + ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenEmptyListOfGroups_returnOk() { + Resource resource = new Resource(); + resource.setGroups(new ArrayList<>()); + ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupsHasNoMembers_returnOk() { + GroupDefinition group1 = new GroupDefinition(); + group1.setMembers(emptyMap()); + GroupDefinition group2 = new GroupDefinition(); + group2.setMembers(emptyMap()); + Resource container = new ResourceBuilder() + .addGroups(group1) + .addGroups(group2) + .build(); + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() { + ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + + @Test + public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() { + verifyAllGroupsHasPrevInstancesAsMembers(); + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null)); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyGroupWithPrevInstanceMemberWereReplaced(); + assertThat(updatedGroupsCaptor.getValue()) + .containsExactlyInAnyOrder(group1, group2); + } + + @Test + public void whenFailingToUpdateGroups_propagateError() { + when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod(); + ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + private void verifyGroupWithPrevInstanceMemberWereReplaced() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void verifyAllGroupsHasPrevInstancesAsMembers() { + assertGroupMembersIds(group1, "inst1", INSTANCE_ID_PRE_CHANGE); + assertGroupMembersIds(group2, "inst1", INSTANCE_ID_PRE_CHANGE, "inst3"); + assertGroupMembersIds(group3, "inst1", "inst3"); + } + + private void assertGroupMembersIds(GroupDefinition group, String ... expectedMembersIds) { + assertThat(group.getMembers()) + .containsValues(expectedMembersIds); + } + + private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) { + GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create(); + Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId)); + groupDefinitionBuilder.setUniqueId(groupId); + return groupDefinitionBuilder.build(); + } + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java new file mode 100644 index 0000000000..0da59d1157 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java @@ -0,0 +1,127 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.impl.utils.TestGenerationUtils.getComponentsUtils; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyTargetsUpdateOperationTest { + + private static final String CONTAINER_ID = "containerId"; + + private PolicyTargetsUpdateOperation policyTargetsUpdateOperation; + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Captor + private ArgumentCaptor> updatedPoliciesCaptor; + private PolicyDefinition policy1, policy2, policy3; + private Resource container; + + @Before + public void setUp() throws Exception { + policy1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2"); + policy2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3"); + policy3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3"); + container = new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .addPolicy(policy3) + .setUniqueId(CONTAINER_ID) + .build(); + policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils()); + } + + @Test + public void whenNoPolicies_returnActionOk() { + Component container = new Resource(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoCmptInstancePolicies_returnOk() { + PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build(); + Component container = new ResourceBuilder().addPolicy(policy).build(); + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build(); + ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(operationStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.OK); + List updatedPolicies = updatedPoliciesCaptor.getValue(); + verifyUpdatedPolicies(updatedPolicies, policy1, policy2);//policy3 does not have "inst2" as target, no update needed + verifyUpdatedPolicyTargets(policy1, "inst1", "inst2New"); + verifyUpdatedPolicyTargets(policy2, "inst1", "inst2New", "inst3"); + } + + @Test + public void whenUpdateOfPoliciesFails_propagateTheFailure() { + ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build(); + ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build(); + when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion); + assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) { + assertThat(updatedPolicy.resolveComponentInstanceTargets()) + .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds); + } + + private void verifyUpdatedPolicies(List updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) { + assertThat(updatedPolicies) + .usingElementComparatorOnFields("targets") + .containsExactlyInAnyOrder(expectedUpdatedPolicies); + } + + private PolicyDefinition createPolicyWithCmptInstAsTargets(String uniqueId, String ... instId) { + PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create(); + Stream.of(instId).forEach(policyDefinitionBuilder::addComponentInstanceTarget); + return policyDefinitionBuilder.setUniqueId(uniqueId).build(); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java new file mode 100644 index 0000000000..ef239f9a2b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.be.components.impl.version; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PostChangeVersionOperationOrchestratorTest { + + private PostChangeVersionOperationOrchestrator testInstance; + @Mock + private PostChangeVersionOperation postChangeVersionOperation1; + @Mock + private PostChangeVersionOperation postChangeVersionOperation2; + @Mock + private PostChangeVersionOperation postChangeVersionOperation3; + + @Before + public void setUp() throws Exception { + testInstance = new PostChangeVersionOperationOrchestrator(asList(postChangeVersionOperation1, postChangeVersionOperation2, postChangeVersionOperation3)); + } + + @Test + public void whenFirstPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation2, postChangeVersionOperation3); + } + + @Test + public void whenAnyPostOperationFails_doNotRunFollowingOperations() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + verifyZeroInteractions(postChangeVersionOperation3); + } + + @Test + public void whenLastPostOperationFails_returnTheFailureResult() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void whenAllOperationsSucceeds_returnOk() { + ComponentInstance newVersion = new ComponentInstance(); + ComponentInstance prevVersion = new ComponentInstance(); + Resource container = new Resource(); + when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK); + ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + } + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java index 31c795478a..cfb5bb59e0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; @@ -35,139 +32,138 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CertificationChangeTransitionTest extends LifecycleTestBase { - private CertificationChangeTransition certifyTransitionObj = null; - private CertificationChangeTransition certificationCancelObj = null; - private CertificationChangeTransition certificationFailObj = null; - - private ComponentsUtils componentsUtils = new ComponentsUtils(); - private User owner = null; - - Resource resource; - - @SuppressWarnings("unchecked") - @Before - public void setup() { - - super.setup(); - componentsUtils.Init(); - // checkout transition object - certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certifyTransitionObj.setConfigurationManager(configurationManager); - certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationCancelObj.setConfigurationManager(configurationManager); - certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - certificationFailObj.setConfigurationManager(configurationManager); - certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); - - owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - resource = createResourceObject(); - } - - @Test - public void testVFCMTStateValidation(){ - Resource resource = createResourceVFCMTObject(); - - User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); - - Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isLeft(), true); - } - - @Test - public void testStateValidationSuccess() { - - Either changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testStateValidationFail() { - - // checkout - Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - assertValidationStateErrorResponse(validateBeforeTransition); - - // checkin - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertValidationStateErrorResponse(validateBeforeTransition); - - // rfc - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertValidationStateErrorResponse(validateBeforeTransition); - - // certified - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertValidationStateErrorResponse(validateBeforeTransition); - - } - - @Test - public void testRolesFail() { - Either changeStateResult; - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); - - modifier.setRole(Role.TESTER.name()); - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testRolesSuccess() { - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(true, validateBeforeTransition.isLeft()); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.ADMIN.name()); - validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(true, validateBeforeTransition.isLeft()); - - } - - private void assertValidationStateErrorResponse(Either validateBeforeTransition) { - assertEquals(validateBeforeTransition.isRight(), true); - ResponseFormat error = validateBeforeTransition.right().value(); - Either changeStateResult = Either.right(error); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + private CertificationChangeTransition certifyTransitionObj = null; + private CertificationChangeTransition certificationCancelObj = null; + private CertificationChangeTransition certificationFailObj = null; + + private User owner = null; + + Resource resource; + + @SuppressWarnings("unchecked") + @Before + public void setup() { + + super.setup(); + // checkout transition object + certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certifyTransitionObj.setConfigurationManager(configurationManager); + certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationCancelObj.setConfigurationManager(configurationManager); + certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + certificationFailObj.setConfigurationManager(configurationManager); + certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation); + + owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + resource = createResourceObject(); + } + + @Test + public void testVFCMTStateValidation(){ + Resource resource = createResourceVFCMTObject(); + + User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null); + + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isLeft(), true); + } + + @Test + public void testStateValidationSuccess() { + + Either changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testStateValidationFail() { + + // checkout + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + assertValidationStateErrorResponse(validateBeforeTransition); + + // checkin + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertValidationStateErrorResponse(validateBeforeTransition); + + // rfc + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertValidationStateErrorResponse(validateBeforeTransition); + + // certified + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertValidationStateErrorResponse(validateBeforeTransition); + + } + + @Test + public void testRolesFail() { + Either changeStateResult; + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRolesSuccess() { + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.ADMIN.name()); + validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(true, validateBeforeTransition.isLeft()); + + } + + private void assertValidationStateErrorResponse(Either validateBeforeTransition) { + assertEquals(validateBeforeTransition.isRight(), true); + ResponseFormat error = validateBeforeTransition.right().value(); + Either changeStateResult = Either.right(error); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java index 5530d4c0f5..f9fb9c83c1 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -38,7 +32,6 @@ import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionAr import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -55,215 +48,219 @@ import org.openecomp.sdc.be.tosca.ToscaExportHandler; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.Silent.class) public class CertificationRequestTest extends LifecycleTestBase { - private ComponentsUtils componentsUtils = new ComponentsUtils(); - @Mock - private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; - @Mock - private ServiceBusinessLogic serviceBusinessLogic; - @Mock - private CapabilityOperation capabilityOperation; - @Mock - private ToscaExportHandler toscaExportUtils; - - private CertificationRequestTransition rfcObj; - - - @Before - public void setup() { - super.setup(); - rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); - // checkout transition object -// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); - // checkoutObj.setAuditingManager(iAuditingManager); - rfcObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - -// Either either = Either.left(toscaRepresentation); -// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); - } - - @Test - public void testVFCMTStateValidation(){ - Either changeStateResult; - Resource resource = createResourceVFCMTObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - User user = new User(); - user.setUserId("cs0008"); - user.setFirstName("Carlos"); - user.setLastName("Santana"); - user.setRole(Role.TESTER.name()); - - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - @Test - public void testCheckoutStateValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = rfcObj.changeStateOperation(resource, user, - // owner, false); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - // changeStateResult = rfcObj.changeStateOperation(resource, user, - // owner, false); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - @Test - public void testAlreadyRfc() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCertificationInProgress() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testAlreadyCertified() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { - Resource resource = new Resource(); - Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - assertTrue(validateAllResourceInstanceCertified.isLeft()); - } - - @Test - public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { - Resource resource = new Resource(); - List riList = new ArrayList(); - ComponentInstance ri = new ComponentInstance(); - ri.setComponentVersion("2.0"); - riList.add(ri); - resource.setComponentInstances(riList); - - Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - assertTrue(validateAllResourceInstanceCertified.isLeft()); - } - - @Test - public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { - Resource resource = createVFWithRI("0.3"); - - simulateCertifiedVersionExistForRI(); - - Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - - assertTrue(validateAllResourceInstanceCertified.isRight()); - ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); - assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); - assertTrue(responseFormat.getMessageId().equals("SVC4559")); - - } - - @Test - public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { - Resource resource = createVFWithRI("1.3"); - - simulateCertifiedVersionExistForRI(); - - Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); - - assertTrue(validateAllResourceInstanceCertified.isRight()); - ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); - assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); - assertTrue(responseFormat.getMessageId().equals("SVC4559")); - - } - - @Test - public void testDeploymentArtifactRestriction() { - Either changeStateResult; - Service service = createServiceObject(false); - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - - Either ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - - Either result = Either.left(service); - Either reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); - Either, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); - when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false)).thenReturn(result); - when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); - changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - } - - private void simulateCertifiedVersionExistForRI() { - Component dummyResource = new Resource(); - Either result = Either.left(dummyResource); - Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); - Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result); - } - - private Resource createVFWithRI(String riVersion) { - Resource resource = new Resource(); - List riList = new ArrayList(); - ComponentInstance ri = new ComponentInstance(); - - ri.setComponentVersion(riVersion); - ri.setComponentUid("someUniqueId"); - riList.add(ri); - resource.setComponentInstances(riList); - return resource; - } + @Mock + private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder; + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + @Mock + private CapabilityOperation capabilityOperation; + @Mock + private ToscaExportHandler toscaExportUtils; + + private CertificationRequestTransition rfcObj; + + + @Before + public void setup() { + super.setup(); + rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao); + // checkout transition object +// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation); + // checkoutObj.setAuditingManager(iAuditingManager); + rfcObj.setConfigurationManager(configurationManager); + +// Either either = Either.left(toscaRepresentation); +// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either); + + } + + @Test + public void testVFCMTStateValidation(){ + Either changeStateResult; + Resource resource = createResourceVFCMTObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + User user = new User(); + user.setUserId("cs0008"); + user.setFirstName("Carlos"); + user.setLastName("Santana"); + user.setRole(Role.TESTER.name()); + + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testCheckoutStateValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + // changeStateResult = rfcObj.changeStateOperation(resource, user, + // owner, false); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + } + + @Test + public void testAlreadyRfc() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testAlreadyCertified() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + Either ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() { + Resource resource = new Resource(); + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() { + Resource resource = new Resource(); + List riList = new ArrayList(); + ComponentInstance ri = new ComponentInstance(); + ri.setComponentVersion("2.0"); + riList.add(ri); + resource.setComponentInstances(riList); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + assertTrue(validateAllResourceInstanceCertified.isLeft()); + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() { + Resource resource = createVFWithRI("0.3"); + + simulateCertifiedVersionExistForRI(); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() { + Resource resource = createVFWithRI("1.3"); + + simulateCertifiedVersionExistForRI(); + + Either validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource); + + assertTrue(validateAllResourceInstanceCertified.isRight()); + ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value(); + assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN); + assertTrue(responseFormat.getMessageId().equals("SVC4559")); + + } + + @Test + public void testDeploymentArtifactRestriction() { + Either changeStateResult; + Service service = createServiceObject(); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + + Either ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + + Either result = Either.left(service); + Either reqCertRes = Either.left(ModelConverter.convertToToscaElement(service)); + Either, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition())); + when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false, true)).thenReturn(result); + when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts); + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes); + changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, true); + assertEquals(changeStateResult.isLeft(), true); + } + + private void simulateCertifiedVersionExistForRI() { + Component dummyResource = new Resource(); + Either result = Either.left(dummyResource); + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource)); + Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result); + } + + private Resource createVFWithRI(String riVersion) { + Resource resource = new Resource(); + List riList = new ArrayList(); + ComponentInstance ri = new ComponentInstance(); + + ri.setComponentVersion(riVersion); + ri.setComponentUid("someUniqueId"); + riList.add(ri); + resource.setComponentInstances(riList); + return resource; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java index 21111ef59e..e60998b177 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java @@ -20,14 +20,11 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; @@ -35,135 +32,133 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CheckinTest extends LifecycleTestBase { - private CheckinTransition checkinObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - - @Before - public void setup() { - - super.setup(); - - // checkout transition object - checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkinObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - } - - @Test - public void testSimpleCheckin() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testSimpleServiceCheckin() { - Either changeStateResult; - Service service = createServiceObject(false); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testCheckinTwiceValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(owner.isLeft()); - // changeStateResult = checkinObj.changeStateOperation(resource, user, - // owner.left().value()); - Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testServiceCheckinTwiceValidation() { - Either changeStateResult; - Service service = createServiceObject(false); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(owner.isLeft()); - - Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCheckoutByAnotherUserValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkinObj.changeStateOperation(resource, - // modifier, owner); - Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testServiceCheckoutByAnotherUserValidation() { - Either changeStateResult; - Service service = createServiceObject(false); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - - service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } + private CheckinTransition checkinObj = null; + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkinObj.setConfigurationManager(configurationManager); + } + + @Test + public void testSimpleCheckin() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testSimpleServiceCheckin() { + Either changeStateResult; + Service service = createServiceObject(); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testCheckinTwiceValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(owner.isLeft()); + // changeStateResult = checkinObj.changeStateOperation(resource, user, + // owner.left().value()); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckinTwiceValidation() { + Either changeStateResult; + Service service = createServiceObject(); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(owner.isLeft()); + + Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCheckoutByAnotherUserValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkinObj.changeStateOperation(resource, + // modifier, owner); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testServiceCheckoutByAnotherUserValidation() { + Either changeStateResult; + Service service = createServiceObject(); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java index 1e3f6f6ce8..0826e5d40c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java @@ -20,16 +20,13 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; @@ -37,153 +34,151 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class CheckoutTest extends LifecycleTestBase { - private CheckoutTransition checkoutObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - @InjectMocks - ResourceBusinessLogic bl = new ResourceBusinessLogic(); - - @Before - public void setup() { - - super.setup(); - - // checkout transition object - checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - checkoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setComponentsUtils(componentsUtils); - - } - - @Test - public void testCheckoutStateValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - assertEquals(changeStateResult.isLeft(), true); - - } - - @Test - public void testAlreadyCheckout() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testCertificationInProgress() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); - - Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); - - assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testReadyForCertification() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - - // if modifier = owner - Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkoutObj.changeStateOperation(resource, user, - // owner); - Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isLeft(), true); - - // else - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - - // admin - modifier.setRole(Role.ADMIN.name()); - // changeStateResult = checkoutObj.changeStateOperation(resource, user, - // owner); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isLeft(), true); - - // designer - modifier.setRole(Role.TESTER.name()); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - - assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - - } - - @Test - public void testRoles() { - Either changeStateResult; - Resource resource = createResourceObject(); - - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); - Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - // changeStateResult = checkoutObj.changeStateOperation(resource, - // modifier, owner); - Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isLeft(), true); - - modifier.setRole(Role.TESTER.name()); - // changeStateResult = checkoutObj.changeStateOperation(resource, - // modifier, owner); - validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); - - } + private CheckoutTransition checkoutObj = null; + @InjectMocks + ResourceBusinessLogic bl = new ResourceBusinessLogic(); + + @Before + public void setup() { + + super.setup(); + // checkout transition object + checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + checkoutObj.setConfigurationManager(configurationManager); + bl.setToscaOperationFacade(toscaOperationFacade); + bl.setComponentsUtils(componentsUtils); + + } + + @Test + public void testCheckoutStateValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + assertEquals(changeStateResult.isLeft(), true); + + } + + @Test + public void testAlreadyCheckout() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testCertificationInProgress() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false); + + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); + + assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testReadyForCertification() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + + // if modifier = owner + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // else + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + + // admin + modifier.setRole(Role.ADMIN.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, user, + // owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isLeft(), true); + + // designer + modifier.setRole(Role.TESTER.name()); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + + assertEquals(changeStateResult.isRight(), true); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + + } + + @Test + public void testRoles() { + Either changeStateResult; + Resource resource = createResourceObject(); + + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); + Either ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + Either validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isLeft(), true); + + modifier.setRole(Role.TESTER.name()); + // changeStateResult = checkoutObj.changeStateOperation(resource, + // modifier, owner); + validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java index bc131ff39a..941af0d728 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java @@ -20,20 +20,13 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletContext; - +import fj.data.Either; import org.junit.BeforeClass; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.openecomp.sdc.AuditingMockManager; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -41,6 +34,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -67,173 +61,185 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.when; public class LifecycleTestBase { - private static Logger log = LoggerFactory.getLogger(LifecycleTestBase.class.getName()); - @InjectMocks - protected final ServletContext servletContext = Mockito.mock(ServletContext.class); - protected IAuditingManager iAuditingManager = null; - protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); - protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; - protected User user = null; - protected Resource resourceResponse; - protected Service serviceResponse; - protected static ConfigurationManager configurationManager = null; - protected ResponseFormatManager responseManager = null; - protected TitanDao titanDao = Mockito.mock(TitanDao.class); - protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - - @BeforeClass - public static void setupClass() { - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - } - - public void setup() { - - // Auditing - iAuditingManager = new AuditingMockManager("lll"); - - // User data and management - user = new User(); - user.setUserId("jh003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); - - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); - when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); - - // Resource Operation mock methods - // getCount - - // createResource - resourceResponse = createResourceObject(); - Either eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); - when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) - .thenAnswer(createAnswer(eitherComponent)); - - Either getOwnerResult = Either.left(user); - when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); - - Either eitherlatestDerived = Either.right(StorageOperationStatus.OK); - when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); - - responseManager = ResponseFormatManager.getInstance(); - - } - - public static Answer createAnswer(final T value) { - Answer dummy = new Answer() { - @Override - public T answer(InvocationOnMock invocation) throws Throwable { - return value; - } - - }; - return dummy; - } - - protected Resource createResourceObject() { - Resource resource = new Resource(); - resource.setName("MyResourceName"); - resource.setUniqueId("uid"); - resource.addCategory("VoIP", "INfra"); - resource.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test"); - resource.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Resource createResourceVFCMTObject() { - ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); - rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); - ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; - - Resource resource = new Resource(cMetadataDataDefinition); - resource.setUniqueId("rid"); - resource.setName("MyResourceVFCMTName"); - resource.addCategory("VoIP", "INfra"); - resource.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test1"); - resource.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("yavivi"); - resource.setIcon("MyIcon.jpg"); - resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); - - return resource; - } - - protected Service createServiceObject(boolean b) { - Service service = new Service(); - service.setName("MyServiceName"); - service.setUniqueId("sid"); - service.addCategory("VoIP", null); - service.setDescription("My short description"); - List tgs = new ArrayList(); - tgs.add("test"); - service.setTags(tgs); - List template = new ArrayList(); - template.add("Root"); - service.setContactId("aa0001"); - service.setIcon("MyIcon.jpg"); - - return service; - } - - protected void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - protected void assertServiceResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { - ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); - ResponseFormat actualResponse = createResponse.right().value(); - } - - protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { - ArtifactDefinition artifact = new ArtifactDefinition(); - - artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); - artifact.setArtifactLabel(logicalName.toLowerCase()); - - return artifact; - } + private static final Logger log = LoggerFactory.getLogger(LifecycleTestBase.class); + @InjectMocks + protected final ServletContext servletContext = Mockito.mock(ServletContext.class); + protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); + protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); + protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class); + protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);; + protected User user = null; + protected Resource resourceResponse; + protected Service serviceResponse; + protected static ConfigurationManager configurationManager = null; + protected ResponseFormatManager responseManager = null; + protected TitanDao titanDao = Mockito.mock(TitanDao.class); + protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + protected static ComponentsUtils componentsUtils; + + @BeforeClass + public static void setupClass() { + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + } + + public void setup() { + +// ExternalConfiguration.setAppName("catalog-be"); +// +// // init Configuration +// String appConfigDir = "src/test/resources/config/catalog-be"; +// ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); +// configurationManager = new ConfigurationManager(configurationSource); + + + // User data and management + user = new User(); + user.setUserId("jh003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + + Either eitherGetUser = Either.left(user); + when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser); + + // Servlet Context attributes + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); + when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation); + when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager); + + // Resource Operation mock methods + // getCount + + // createResource + resourceResponse = createResourceObject(); + Either eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse)); + when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class))) + .thenAnswer(createAnswer(eitherComponent)); + + Either getOwnerResult = Either.left(user); + when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult); + + Either eitherlatestDerived = Either.right(StorageOperationStatus.OK); + when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived); + + responseManager = ResponseFormatManager.getInstance(); + + } + + public static Answer createAnswer(final T value) { + Answer dummy = new Answer() { + @Override + public T answer(InvocationOnMock invocation) throws Throwable { + return value; + } + + }; + return dummy; + } + + protected Resource createResourceObject() { + Resource resource = new Resource(); + resource.setUniqueId("uid"); + resource.setName("MyResourceName"); + resource.setUniqueId("uid"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Resource createResourceVFCMTObject() { + ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition(); + rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT); + ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ; + + Resource resource = new Resource(cMetadataDataDefinition); + resource.setUniqueId("rid"); + resource.setName("MyResourceVFCMTName"); + resource.addCategory("VoIP", "INfra"); + resource.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test1"); + resource.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + resource.setDerivedFrom(template); + resource.setVendorName("Motorola"); + resource.setVendorRelease("1.0.0"); + resource.setContactId("yavivi"); + resource.setIcon("MyIcon.jpg"); + resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue()); + + return resource; + } + + protected Service createServiceObject() { + Service service = new Service(); + service.setName("MyServiceName"); + service.setUniqueId("sid"); + service.addCategory("VoIP", null); + service.setDescription("My short description"); + List tgs = new ArrayList(); + tgs.add("test"); + service.setTags(tgs); + List template = new ArrayList(); + template.add("Root"); + service.setContactId("aa0001"); + service.setIcon("MyIcon.jpg"); + + return service; + } + + protected void assertResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + protected void assertServiceResponse(Either createResponse, ActionStatus expectedStatus, String... variables) { + ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables); + ResponseFormat actualResponse = createResponse.right().value(); + } + + protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) { + ArtifactDefinition artifact = new ArtifactDefinition(); + + artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase())); + artifact.setArtifactLabel(logicalName.toLowerCase()); + + return artifact; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java index 11913ad31a..d5d665809d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java @@ -20,105 +20,100 @@ package org.openecomp.sdc.be.components.lifecycle; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class UndoCheckoutTest extends LifecycleTestBase { - private UndoCheckoutTransition undoCheckoutObj = null; - private ComponentsUtils componentsUtils = new ComponentsUtils(); - - @Before - public void setup() { + private UndoCheckoutTransition undoCheckoutObj = null; - super.setup(); + @Before + public void setup() { - // checkout transition object - undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); - undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); - undoCheckoutObj.setConfigurationManager(configurationManager); - componentsUtils.Init(); + super.setup(); + // checkout transition object + undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao); + undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation); + undoCheckoutObj.setConfigurationManager(configurationManager); - } + } - @Test - public void testResourceNotCheckedOutValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); + @Test + public void testResourceNotCheckedOutValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); - Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); + Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); - validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION); + validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + } - @Test - public void testDifferentResourceOwnerValidation() { - Either changeStateResult; - Resource resource = createResourceObject(); + @Test + public void testDifferentResourceOwnerValidation() { + Either changeStateResult; + Resource resource = createResourceObject(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - User modifier = new User(); - modifier.setUserId("modifier"); - modifier.setFirstName("Albert"); - modifier.setLastName("Einstein"); - modifier.setRole(Role.DESIGNER.name()); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + User modifier = new User(); + modifier.setUserId("modifier"); + modifier.setFirstName("Albert"); + modifier.setLastName("Einstein"); + modifier.setRole(Role.DESIGNER.name()); - Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); - assertTrue(ownerResponse.isLeft()); - User owner = ownerResponse.left().value(); - Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - assertEquals(validateBeforeTransition.isRight(), true); - changeStateResult = Either.right(validateBeforeTransition.right().value()); - assertEquals(changeStateResult.isRight(), true); + Either ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE); + assertTrue(ownerResponse.isLeft()); + User owner = ownerResponse.left().value(); + Either validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + assertEquals(validateBeforeTransition.isRight(), true); + changeStateResult = Either.right(validateBeforeTransition.right().value()); + assertEquals(changeStateResult.isRight(), true); - assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); - } + assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java index ab2e865ae0..89b82b91d2 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java @@ -1,14 +1,7 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - +import com.google.common.collect.Sets; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -24,9 +17,14 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class GlobalInputsFilteringBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java index a00b0b8e8a..ec741b4953 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; - -import java.util.Arrays; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -18,7 +11,13 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; -import fj.data.Either; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs; public class GlobalTypesMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java index 773b068cd7..d50f4859db 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; @@ -14,14 +9,23 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class RelationsComparatorTest { public static final String INSTANCE1 = "instance1"; public static final String INSTANCE2 = "instance2"; RelationsComparator testInstance; - private RequirementCapabilityRelDef relation1, relation2, relation3, relation4; - private ComponentInstance componentInstance1, componentInstance2; + private RequirementCapabilityRelDef relation1; + private RequirementCapabilityRelDef relation2; + private RequirementCapabilityRelDef relation3; + private RequirementCapabilityRelDef relation4; + private ComponentInstance componentInstance1; + private ComponentInstance componentInstance2; @Before public void setUp() { @@ -59,21 +63,21 @@ public class RelationsComparatorTest { @Test public void isRelationsChanged_notSameType() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().getRelationship().setType("someDiffType"); + relation2DifType.resolveSingleRelationship().getRelation().getRelationship().setType("someDiffType"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameCapability() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); + relation2DifType.resolveSingleRelationship().getRelation().setCapabilityUid("someDiffUid"); isRelationsChangedTest(relation2DifType); } @Test public void isRelationsChanged_notSameReqName() throws Exception { RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1); - relation2DifType.getSingleRelationship().getRelation().setRequirement("someDiffReq"); + relation2DifType.resolveSingleRelationship().getRelation().setRequirement("someDiffReq"); isRelationsChangedTest(relation2DifType); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java index 3b1ed52550..298a4454b3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java @@ -1,10 +1,6 @@ package org.openecomp.sdc.be.components.merge; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -20,7 +16,10 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class TopologyComparatorTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java new file mode 100644 index 0000000000..be9f426c2c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java @@ -0,0 +1,113 @@ +package org.openecomp.sdc.be.components.merge.capability; + +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import java.util.Map; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleCapabilityResolverTest { + + public static final String NEW_OWNER_ID1 = "owner1"; + public static final String NEW_OWNER_ID2 = "owner2"; + public static final String OLD_OWNER_ID1 = "oldOwner1"; + private static final String OLD_OWNER_ID2 = "oldOwner2"; + public static final String OLD_OWNER_ID3 = "oldOwner3"; + @InjectMocks + private SimpleCapabilityResolver testInstance; + @Mock + private MergeInstanceUtils MergeInstanceUtils; + + private CapabilityDefinition capName1Owner1Type1; + private CapabilityDefinition capName1Owner1Type2; + private CapabilityDefinition capName1Owner2Type1; + private CapabilityDefinition capName2Owner1Type2; + + private CapabilityDefinition prevCapName1Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type2; + private CapabilityDefinition prevCapName1Owner2Type1; + private CapabilityDefinition prevCapName2Owner1Type2; + private CapabilityDefinition prevCapName1Owner3Type1; + private CapabilityDefinition prevCapName3Owner1Type1; + private CapabilityDefinition prevCapName1Owner1Type3; + CapabilityDefinition[] prevCapabilities; + private ComponentInstance oldInstance; + private ComponentInstance currInstance; + + + @Before + public void setUp() { + capName1Owner1Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type1 = new CapabilityDefinition(capName1Owner1Type1); + prevCapName1Owner1Type1.setOwnerId(OLD_OWNER_ID1); + + capName1Owner1Type2 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName1Owner1Type2 = new CapabilityDefinition(capName1Owner1Type2); + prevCapName1Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + capName1Owner2Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID2).setType("type1").build(); + prevCapName1Owner2Type1 = new CapabilityDefinition(capName1Owner2Type1); + prevCapName1Owner2Type1.setOwnerId(OLD_OWNER_ID2); + + capName2Owner1Type2 = new CapabilityDefinitionBuilder().setName("name2").setOwnerId(NEW_OWNER_ID1).setType("type2").build(); + prevCapName2Owner1Type2 = new CapabilityDefinition(capName2Owner1Type2); + prevCapName2Owner1Type2.setOwnerId(OLD_OWNER_ID1); + + //prev capabilities that are not mapped to any new capability + prevCapName1Owner3Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID3).setType("type1").build(); + prevCapName3Owner1Type1 = new CapabilityDefinitionBuilder().setName("name3").setOwnerId(OLD_OWNER_ID1).setType("type1").build(); + prevCapName1Owner1Type3 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID1).setType("type3").build(); + + currInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(capName1Owner1Type1, capName1Owner1Type2, capName1Owner2Type1, capName2Owner1Type2).build(); + prevCapabilities = new CapabilityDefinition[]{prevCapName1Owner1Type1, prevCapName1Owner1Type2, prevCapName1Owner2Type1, prevCapName2Owner1Type2, prevCapName1Owner3Type1, prevCapName3Owner1Type1, prevCapName1Owner1Type3}; + oldInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(prevCapabilities).build(); + } + + @Test + public void resolvePrevCapIdToNewCapability_resolveByTypeNameAndNewOwnerId() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } + + @Test + public void resolvePrevCapIdToNewCapability_noMatchingNewOwnerIds() { + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(emptyMap()); + Map oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance); + assertThat(oldToNewMap).isEmpty(); + } + + @Test + public void mapOldToNewInstanceCapabilitiesOwnerIds() { + Resource container = new ResourceBuilder().addComponentInstance(currInstance).build(); + Resource prevInstanceOrigNode = new Resource(); + when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, "inst1", asList(OLD_OWNER_ID1, OLD_OWNER_ID2, OLD_OWNER_ID3))).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2)); + Map oldToNewMap = testInstance.resolvePrevCapToNewCapability(container, prevInstanceOrigNode, "inst1", asList(prevCapabilities)); + assertThat(oldToNewMap).hasSize(4); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2); + assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1); + assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java index bcdd08e95b..c75a6ccd5d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java @@ -1,12 +1,5 @@ package org.openecomp.sdc.be.components.merge.heat; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.ArtifactBuilder; @@ -15,6 +8,13 @@ import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + public class HeatEnvArtifactsMergeBusinessLogicTest { private HeatEnvArtifactsMergeBusinessLogic testInstance; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java index 26b6782918..30801b0a4a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java @@ -1,14 +1,6 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.ListUtils; import org.junit.Before; import org.junit.Test; @@ -22,7 +14,14 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class ComponentInputsMergeBLTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java index b0124e4e44..98fceab7a8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java @@ -1,26 +1,24 @@ package org.openecomp.sdc.be.components.merge.input; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class InputsValuesMergingBusinessLogicTest { public static final String INPUT_DEFUALT_TYPE = "string"; @@ -133,54 +131,4 @@ public class InputsValuesMergingBusinessLogicTest { inputDef.setOwnerId("owner"); return inputDef; } - - private void addInstanceProperty(Resource resource, ComponentInstanceProperty prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesProperties(), prop, instanceId); - } - - private void addInstanceInput(Resource resource, ComponentInstanceInput prop, String instanceId) { - addInstancePropDefinition(resource.getComponentInstancesInputs(), prop, instanceId); - } - - private void addInstancePropDefinition(Map> propsDefinitions, T propDef, String instanceId) { - propsDefinitions.computeIfAbsent(instanceId, id -> new ArrayList<>()).add(propDef); - } - - private Resource createResourceWithInputs(String ... inputsIds) { - Resource resource = new Resource(); - List inputs = new ArrayList<>(); - for (String inputId : inputsIds) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setOwnerId("cs0008"); - inputDefinition.setUniqueId(inputId); - inputs.add(inputDefinition); - } - resource.setInputs(inputs); - return resource; - } - - - private ComponentInstanceProperty createGetInputComponentProperty(String ... declaredToInputId) { - ComponentInstanceProperty prevDeclaredProperty = new ComponentInstanceProperty(); - for (String inputId : declaredToInputId) { - addGetInputValueOnProp(inputId, prevDeclaredProperty); - } - - return prevDeclaredProperty; - } - - private void addGetInputValueOnProp(String declaredToInputId, PropertyDataDefinition declaredProperty) { - GetInputValueDataDefinition getInputDef = new GetInputValueDataDefinition(); - getInputDef.setInputId(declaredToInputId); - if (declaredProperty.getGetInputValues() == null) { - declaredProperty.setGetInputValues(new ArrayList<>()); - } - declaredProperty.getGetInputValues().add(getInputDef); - } - - private ComponentInstanceInput createGetInputComponentInstanceInput(String declaredToInputId) { - ComponentInstanceInput prevDeclaredProp = new ComponentInstanceInput(); - addGetInputValueOnProp(declaredToInputId, prevDeclaredProp); - return prevDeclaredProp; - } } \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java index be16bc3621..df3e0ddb68 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java @@ -1,10 +1,5 @@ package org.openecomp.sdc.be.components.merge.instance; -import static junit.framework.TestCase.assertEquals; - -import java.util.HashMap; -import java.util.Map; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -14,6 +9,11 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.Resource; +import java.util.HashMap; +import java.util.Map; + +import static groovy.util.GroovyTestCase.assertEquals; + public class ComponentInstanceArtifactsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java new file mode 100644 index 0000000000..4fbb1ab5d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabiliteisPropertiesMergeTest { + + @InjectMocks + private ComponentInstanceCapabiliteisPropertiesMerge testInstance; + + @Mock + private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL; + + @Mock + private ComponentsUtils componentsUtils; + + private DataForMergeHolder mergeHolder; + + private Resource origInstanceNode; + private List origInstanceCapabilities; + + @Before + public void setUp() throws Exception { + origInstanceNode = new Resource(); + origInstanceCapabilities = Collections.emptyList(); + mergeHolder = new DataForMergeHolder(); + mergeHolder.setOrigInstanceNode(origInstanceNode); + mergeHolder.setOrigInstanceCapabilities(origInstanceCapabilities); + } + + @Test + public void mergeDataAfterCreate() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.OK); + Either mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isLeft()); + } + + @Test + public void mergeDataAfterCreate_error() { + Service currentComponent = new Service(); + when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities)) + .thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat()); + Either mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId"); + assertTrue(mergeResult.isRight()); + } + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java new file mode 100644 index 0000000000..d73459c1b1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java @@ -0,0 +1,275 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import com.google.common.collect.ImmutableMap; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.components.merge.capability.SimpleCapabilityResolver; +import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic; +import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.ComponentInstancePropertyBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceCapabilitiesMergeBLTest { + + private static final String INSTANCE1 = "inst1"; + private static final String INSTANCE2 = "inst2"; + + private ComponentCapabilitiesPropertiesMergeBL testInstance; + private ComponentsUtils componentsUtils; + @Mock + private SimpleCapabilityResolver capabilityResolver; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic; + @Captor + private ArgumentCaptor> prevCapPropertiesCaptor; + @Captor + private ArgumentCaptor> currCapPropertiesCaptor; + @Captor + private ArgumentCaptor getCurrResourceFilterCapture; + + private CapabilityDefinition oldCap; + private CapabilityDefinition oldCap2; + private CapabilityDefinition newCap; + private CapabilityDefinition newCap2; + + private ComponentParametersView getCapabilitiesPropsFilter; + + protected static ConfigurationManager configurationManager = null; + + @Before + public void setUp() throws Exception { + oldCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .build(); + + oldCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE1) + .setOwnerName(INSTANCE1) + .setId("cap1") + .setType("type1") + .setName("cap1") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build()) + .build(); + + newCap2 = new CapabilityDefinitionBuilder() + .setOwnerId(INSTANCE2) + .setOwnerName(INSTANCE2) + .setId("cap2") + .setType("type1") + .setName("cap2") + .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build()) + .addProperty(new ComponentInstancePropertyBuilder().setName("prop3").build()) + .build(); + + getCapabilitiesPropsFilter = new ComponentParametersView(); + getCapabilitiesPropsFilter.disableAll(); + getCapabilitiesPropsFilter.setIgnoreComponentInstances(false); + getCapabilitiesPropsFilter.setIgnoreCapabilities(false); + getCapabilitiesPropsFilter.setIgnoreCapabiltyProperties(false); + + ExternalConfiguration.setAppName("catalog-be"); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + testInstance = new ComponentCapabilitiesPropertiesMergeBL(dataDefinitionsValuesMergingBusinessLogic, toscaOperationFacade, componentsUtils, capabilityResolver); + } + + @Test + public void mergeCapabilityProperties_singleCapability() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), getCurrResourceFilterCapture.capture())).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + assertThat(getCurrResourceFilterCapture.getValue()).isEqualToComparingFieldByField(getCapabilitiesPropsFilter); + } + + @Test + public void mergeCapabilityProperties_failToGetResourceWithPropsCapabilities() { + Resource currResource = new ResourceBuilder().setUniqueId("rid").build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + ActionStatus actionStatus = testInstance.mergeComponents(new Resource(), currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND); + } + + @Test + public void mergeCapabilityProperties_multipleCapabilitiesToMerge() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance prevInst2 = new ComponentInstanceBuilder().addCapability(oldCap2).setName(oldCap2.getOwnerName()).build(); + + ComponentInstance currInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build(); + ComponentInstance currInst2 = new ComponentInstanceBuilder().addCapability(newCap2).setName(newCap2.getOwnerName()).build(); + + Resource currResource = new ResourceBuilder().addComponentInstance(currInst1).addComponentInstance(currInst2).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).addComponentInstance(prevInst2).build(); + when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(currResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, currInst1)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst2, currInst2)).thenReturn(ImmutableMap.of(oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, currResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeCapabilityProperties_noNewCapabilitiesResolved() { + ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + ComponentInstance newInst1 = new ComponentInstanceBuilder().setName(oldCap.getOwnerName()).build(); + Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build(); + Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_noPrevCapabilitiesToMerge() { + Resource newResource = new Resource(); + Resource prevResource = new Resource(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + verifyNoMoreInteractions(toscaOperationFacade); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } + + @Test + public void mergeCapabilityProperties_failedToUpdateComponent() { + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build(); + Resource newResource = new Resource(); + Resource prevResource = new ResourceBuilder().addComponentInstance(inst1).build(); + when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource)); + when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + //////////////////////////// + @Test + public void mergeInstanceCapabilityProperties_singleCap() { + List previousInstanceCapabilities = Collections.singletonList(oldCap); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, newCap.getOwnerId())).thenReturn(StorageOperationStatus.OK); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap)); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture()); + + assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2"); + assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1"); + } + + @Test + public void mergeInstanceCapabilityProperties() { + List previousInstanceCapabilities = Arrays.asList(oldCap, oldCap2); + ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).addCapability(newCap2).setId(newCap.getOwnerId()).build(); + Resource container = new ResourceBuilder().addComponentInstance(inst1).build(); + Resource origInstanceNode = new Resource(); + when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap, oldCap2, newCap2)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList()); + } + + @Test + public void mergeInstanceCapabilityProperties_emptyCapabilitiesList() { + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(new Resource(), new Resource(), "instanceId", Collections.emptyList()); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(toscaOperationFacade, dataDefinitionsValuesMergingBusinessLogic, capabilityResolver); + } + + @Test + public void mergeInstanceCapabilityProperties_failedToUpdateComponent() { + Resource container = new Resource(); + Resource resource = new Resource(); + List capList = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, capList)).thenReturn(ImmutableMap.of(oldCap, newCap)); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.GENERAL_ERROR); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, capList); + assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR); + } + + @Test + public void mergeInstanceCapabilityProperties_noNewCapabilitiesFound() { + Resource container = new Resource(); + Resource resource = new Resource(); + List prevCapabilities = singletonList(oldCap); + when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, prevCapabilities)).thenReturn(emptyMap()); + when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK); + ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, prevCapabilities); + assertThat(actionStatus).isEqualTo(ActionStatus.OK); + verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java index 2101ea49ab..115825733e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -26,7 +19,13 @@ import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Mockito.when; public class ComponentInstanceHeatEnvMergeTest { @@ -67,7 +66,7 @@ public class ComponentInstanceHeatEnvMergeTest { for (ArtifactDefinition mergedArtifact : mergedArtifacts) { Map json = new HashMap<>(); when(artifactsBusinessLogicMock.buildJsonForUpdateArtifact(mergedArtifact, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(json); - ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update); + ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE); when(artifactsBusinessLogicMock.updateResourceInstanceArtifactNoContent(Mockito.eq(instanceId), Mockito.eq(resource), Mockito.eq(USER), Mockito.eq(json), Mockito.refEq(artifactUpdateOperation), diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java index bc3efe423d..630a43ef2d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java @@ -1,13 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -29,7 +22,13 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceMergeDataBusinessLogicTest { @@ -112,4 +111,6 @@ public class ComponentInstanceMergeDataBusinessLogicTest { assertFalse(value.isIgnoreArtifacts()); } + + } \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java index cb3d506bfc..d946206f23 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java @@ -1,16 +1,6 @@ package org.openecomp.sdc.be.components.merge.instance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyListOf; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -19,8 +9,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -37,7 +25,16 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.exception.ResponseFormat; -import fj.data.Either; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropsAndInputsMergeTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java new file mode 100644 index 0000000000..08c8456064 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java @@ -0,0 +1,378 @@ +package org.openecomp.sdc.be.components.merge.instance; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstanceRelationMergeTest { + private ComponentInstanceRelationMerge compInstanceRelationMerge; + @Mock + private DataForMergeHolder dataHolder; + private Component containerComponent; + private Component updatedContainerComponent; + private ComponentInstance currentResourceInstance; + + private RequirementCapabilityRelDef requirementDef1; + private RequirementCapabilityRelDef requirementDef2; + private RequirementCapabilityRelDef capabilityDef1; + private RequirementCapabilityRelDef capabilityDef2; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private User user; + + @Captor + ArgumentCaptor argumentCaptor; + + + @Before + public void startUp() { + compInstanceRelationMerge = new ComponentInstanceRelationMerge(); + compInstanceRelationMerge.setToscaOperationFacade(toscaOperationFacade); + + MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + compInstanceRelationMerge.setMergeInstanceUtils(mergeInstanceUtils); + + containerComponent = new Service(); + List resourceInstancesRelations = new ArrayList<>(); + + requirementDef1 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF2.VFI_1", "SRV1.VF1.VFC_1.VFCI_1", "Requirement1"); + resourceInstancesRelations.add(requirementDef1); + requirementDef2 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF3.VFI_1", "SRV1.VF1.VFC_2.VFCI_2", "Requirement2"); + resourceInstancesRelations.add(requirementDef2); + + + capabilityDef1 = createCapabilityDef("SRV1.VF4.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_3.VFCI_3", "Capability3"); + resourceInstancesRelations.add(capabilityDef1); + capabilityDef2 = createCapabilityDef("SRV1.VF5.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_4.VFCI_1", "Capability4"); + resourceInstancesRelations.add(capabilityDef2); + + containerComponent.setComponentInstancesRelations(resourceInstancesRelations ); + + currentResourceInstance = new ComponentInstance(); + currentResourceInstance.setUniqueId("SRV1.VF1.VFI_1"); + currentResourceInstance.setComponentUid("SRV1.VF1"); + currentResourceInstance.setIsProxy(false); + + updatedContainerComponent = new Service(); + updatedContainerComponent.setUniqueId("123123123123123123"); + } + + @Test + public void testSaveDataBeforeMerge() { + Resource vf = new Resource(); + + List vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + compInstanceRelationMerge.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, vf); + + verify(dataHolder).setVfRelationsInfo(argumentCaptor.capture()); + VfRelationsMergeInfo relationsMergeInfo = argumentCaptor.getValue(); + List fromRelationsMergeInfo = relationsMergeInfo.getFromRelationsInfo(); + List toRelationsMergeInfo = relationsMergeInfo.getToRelationsInfo(); + + assertNotNull("Expected not null list of relations merge info", fromRelationsMergeInfo); + assertNotNull("Expected not null list of relations merge info", toRelationsMergeInfo); + + assertEquals("Expected 2 elements", 2, fromRelationsMergeInfo.size()); + assertEquals("Expected 1 elements", 1, toRelationsMergeInfo.size()); + } + + @Test + public void testMergeDataAfterCreate_NoSavedData() { + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + List relations = updatedContainerComponent.getComponentInstancesRelations(); + assertNull("Expected no relations", relations); + } + + @Test + public void testMergeDataAfterCreate() { + Resource vf = new Resource(); + + List vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List fromRelationsMergeInfo = new ArrayList<>(); + List toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_1", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_1", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + + @Test + public void testMergeDataAfterCreate_OwnerChanged() { + Resource vf = new Resource(); + + List vfcInstances = new ArrayList<>(); + vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_2", "SRV1.VF1.VFC_1", true)); + vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true)); + vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false)); + vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_2", "SRV1.VF1.VFC_4", true)); + vf.setComponentInstances(vfcInstances); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + Either eitherVF = Either.left(vf); + when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF); + + + List fromRelationsMergeInfo = new ArrayList<>(); + List toRelationsMergeInfo = new ArrayList<>(); + + RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1); + fromRelationsMergeInfo.add(relationMergeInfo1); + RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2); + toRelationsMergeInfo.add(relationMergeInfo2); + + VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo); + + when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo); + + List componentInstances = new ArrayList<>(); + componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2")); + componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1")); + componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1")); + componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1")); + componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1")); + updatedContainerComponent.setComponentInstances(componentInstances); + + List resourceInstancesRelations = new ArrayList<>(); + updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations); + + when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK); + + compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2"); + + verify(dataHolder).getVfRelationsMergeInfo(); + verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList()); + + List relations = updatedContainerComponent.getComponentInstancesRelations(); + assertEquals("Expected 2 relations", 2, relations.size()); + + + RequirementCapabilityRelDef capabilityRelDef = relations.get(0); + assertEquals("SRV1.VF1.VFC_4.VFCI_2", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId()); + assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode()); + assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode()); + + RequirementCapabilityRelDef requirementRelDef = relations.get(1); + assertEquals("SRV1.VF1.VFC_1.VFCI_2", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId()); + assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode()); + assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode()); + } + + + /** + * @param vfId + * @param vfiUniqueId + * @return + */ + private ComponentInstance createVfi(String vfId, String vfiUniqueId) { + ComponentInstance vfi = new ComponentInstance(); + vfi.setUniqueId(vfiUniqueId); + vfi.setComponentUid(vfId); + + Resource vf = new Resource(); + vf.setUniqueId(vfId); + return vfi; + } + + private ComponentInstance createVfci(String name, String uniqueId, String componentUid, boolean foundVfc) { + ComponentInstance compInst = new ComponentInstance(); + compInst.setName(name); + compInst.setUniqueId(uniqueId); + compInst.setComponentUid(componentUid); + + if(foundVfc) { + createVfc(componentUid); + } + else { + failLoadVfc(componentUid); + } + return compInst; + } + + private void failLoadVfc(String uid) { + Either eitherVFC = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + } + + private Component createVfc(String uid) { + Resource vfc = new Resource(); + vfc.setUniqueId(uid); + + Map> capabilities = new HashMap<>(); + Map> requirements = new HashMap<>();; + IntStream.range(0, 5).forEach(i -> { + + List capList = new LinkedList<>(); + capList.add(null); + CapabilityDefinition capDef = new CapabilityDefinition(); + capDef.setName("CapabilityName" + i); + capDef.setUniqueId("Capability" + i); + capDef.setType("CapabilityType" + i); + capList.add(capDef); + capabilities.put("Key" + i, capList); + + List reqList = new LinkedList<>(); + reqList.add(null); + RequirementDefinition reqDef = new RequirementDefinition(); + reqDef.setName("RequirementName" + i); + reqDef.setUniqueId("Requirement" + i); + reqDef.setCapability("CapabilityType" + i); + reqList.add(reqDef); + requirements.put("Key" + i, reqList); + + }); + vfc.setCapabilities(capabilities ); + vfc.setRequirements(requirements); + + Either eitherVFC = Either.left(vfc); + when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC); + + return vfc; + } + + private RequirementCapabilityRelDef createRequirementCapabilityDef(String fromNode, String toNode) { + RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef(); + + reqCapDef.setFromNode(fromNode); + reqCapDef.setToNode(toNode); + + List relationships = new ArrayList<>(); + CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship(); + relationships.add(capabilityRequirementRelationship); + reqCapDef.setRelationships(relationships); + + return reqCapDef; + } + + private RequirementCapabilityRelDef createRequirementDef(String fromNode, String toNode, String ownerId, String requirementUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setRequirementOwnerId(ownerId); + relationshipInfo.setRequirementUid(requirementUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + + + return reqCapDef; + } + + private RequirementCapabilityRelDef createCapabilityDef(String fromNode, String toNode, String ownerId, String capabilityUid) { + RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode); + CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship(); + + RelationshipInfo relationshipInfo = new RelationshipInfo(); + relationshipInfo.setCapabilityOwnerId(ownerId); + relationshipInfo.setCapabilityUid(capabilityUid); + relationshipInfo.setRelationships(new RelationshipImpl()); + capabilityRequirementRelationship.setRelation(relationshipInfo ); + + return reqCapDef; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java new file mode 100644 index 0000000000..65ab3ec121 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.components.merge.path; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceForwardingPathMerge; +import org.openecomp.sdc.be.components.path.BaseForwardingPathVersionChangeTest; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Set; + +import static groovy.util.GroovyTestCase.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.TestCase.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.when; + +public class ComponentInstanceForwardingPathMergeTest extends BaseForwardingPathVersionChangeTest { + + @InjectMocks + private ComponentInstanceForwardingPathMerge testInstance; + + @Mock + private ServiceBusinessLogic serviceBusinessLogic; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + private User user; + + @Before + public void setUpData() { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId("44"); + user.setRole(UserRoleEnum.ADMIN.getName()); + } + + @Test + public void testIgnoreMergeSinceItIsNotService() { + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, newNodeAC, "3344"); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(newNodeAC, componentResponseFormatEither.left().value()); + } + + @Test + public void mergeShouldDelete() { + Set forwardingPathNamesToDeleteOnComponentInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeACI.getUniqueId()); + nodeACI.getCapabilities().clear(); + newNodeAC.getCapabilities().clear(); + when(serviceBusinessLogic.deleteForwardingPaths(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(forwardingPathNamesToDeleteOnComponentInstanceDeletion)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + Either componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + assertEquals(0, ((Service) componentResponseFormatEither.left().value()).getForwardingPaths().size()); + } + + @Test + public void mergeShouldUpdate() { + when(serviceBusinessLogic.updateForwardingPath(any(), any(), any(), anyBoolean())) + .thenReturn(Either.left(service)); + when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC)); + testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC); + assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId()); + + // Change internal ci, just like change version do + service.getComponentInstances().remove(nodeACI); + service.getComponentInstances().add(newNodeACI); + + Either componentResponseFormatEither = testInstance + .mergeDataAfterCreate(user, dataHolder, service, newNodeA); + assertNotNull(componentResponseFormatEither); + assertTrue(componentResponseFormatEither.isLeft()); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java index 0a858c9a29..bbb2dd6895 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceInputsMergeBL; import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -23,7 +17,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstanceInputsMergeBLTest { @@ -41,7 +41,8 @@ public class ComponentInstanceInputsMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -71,22 +72,22 @@ public class ComponentInstanceInputsMergeBLTest { @Test public void mergeInstancesInputs() throws Exception { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @Test - public void mergeInstancesInputs_failure() throws Exception { + public void mergeInstancesInputs_failure() { when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } @Test - public void mergeInstanceProps() throws Exception { + public void mergeInstanceProps() { List newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) @@ -97,7 +98,7 @@ public class ComponentInstanceInputsMergeBLTest { } @Test - public void mergeInstanceProps_failure() throws Exception { + public void mergeInstanceProps_failure() { List newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1); List oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1); when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs)) diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java index 7948ab8a3d..6013009106 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java @@ -1,18 +1,12 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.merge.instance.ComponentInstancePropertiesMergeBL; import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -21,7 +15,13 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import fj.data.Either; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class ComponentInstancePropertiesMergeBLTest { @@ -40,7 +40,8 @@ public class ComponentInstancePropertiesMergeBLTest { @Mock private ComponentsUtils componentsUtils; - private Resource oldResource, newResource; + private Resource oldResource; + private Resource newResource; @Before public void setUp() throws Exception { @@ -64,7 +65,7 @@ public class ComponentInstancePropertiesMergeBLTest { public void mergeInstancesPropsAndInputs_mergeInstanceProps() throws Exception { when(toscaOperationFacade.updateComponentInstancePropsToComponent(newResource.getComponentInstancesProperties(), newResource.getUniqueId())) .thenReturn(Either.left(Collections.emptyMap())); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(actionStatus, ActionStatus.OK); verifyMergeBLCalled(oldResource, newResource); } @@ -75,7 +76,7 @@ public class ComponentInstancePropertiesMergeBLTest { .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR); verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic); - ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource); + ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java index 8669a781b4..3b079d30d5 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java @@ -1,21 +1,22 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionAbstractBuilder; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.model.InputDefinition; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.verify; + public class DataDefinitionsValuesMergingBusinessLogicTest { private static final String DEFAULT_PROP_TYPE = "string"; @@ -110,9 +111,10 @@ public class DataDefinitionsValuesMergingBusinessLogicTest { } private PropertyDataDefinition createGetInputPropertyDataDefinition(String name, String ... inputsNames) { - PropertyDataDefinitionBuilder propertyBuilder = new PropertyDataDefinitionBuilder() + PropertyDataDefinitionAbstractBuilder propertyBuilder = new PropertyDataDefinitionBuilder() .setName(name) .setType(DEFAULT_PROP_TYPE); + for (String inputName : inputsNames) { propertyBuilder.addGetInputValue(inputName); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java index 6faee487f4..5c23ec0e8c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java @@ -1,17 +1,6 @@ package org.openecomp.sdc.be.components.merge.property; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -25,7 +14,17 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import fj.data.Either; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class PropertyDataValueMergeBusinessLogicTest { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java index 8e7949f108..0590c7e500 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java @@ -1,82 +1,63 @@ package org.openecomp.sdc.be.components.merge.resource; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; - import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL; -import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) public class ResourceDataMergeBusinessLogicTest { @InjectMocks private ResourceDataMergeBusinessLogic testInstance; @Mock - private ComponentInstanceInputsMergeBL instanceInputsValueMergeBLMock; + private ComponentsMergeCommand commandA; @Mock - private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBLMock; + private ComponentsMergeCommand commandB; @Mock - private ComponentInputsMergeBL inputsValueMergeBLMock; + private ComponentsMergeCommand commandC; @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + testInstance = new ResourceDataMergeBusinessLogic(Arrays.asList(commandA, commandB, commandC)); } @Test - public void mergeResourceInputs_allMergeClassesAreCalled() throws Exception { + public void mergeResources_allMergeClassesAreCalled() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.OK); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandB.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); + when(commandC.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.OK, actionStatus); } @Test - public void mergeResourceInputs_failToMergeProperties_dontCallOtherMergeMethods() throws Exception { + public void mergeResources_mergeCommandFailed_dontCallOtherMergeMethods() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); + when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(instanceInputsValueMergeBLMock, inputsValueMergeBLMock); + verify(commandA).description(); + verifyZeroInteractions(commandB, commandC); } - @Test - public void mergeResourceInputs_failToMergeInstanceInputs_dontCallOtherMergeMethods() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - verifyZeroInteractions(inputsValueMergeBLMock); - } - - @Test - public void mergeResourceInputs_failedToMergeInputs() throws Exception { - Resource oldResource = ObjectGenerator.buildBasicResource(); - Resource newResource = ObjectGenerator.buildBasicResource(); - when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK); - when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.GENERAL_ERROR); - ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); - assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); - } } \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java new file mode 100644 index 0000000000..3131c4987c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java @@ -0,0 +1,328 @@ +package org.openecomp.sdc.be.components.merge.utils; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class MergeInstanceUtilsTest { + private MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils(); + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Before + public void startUp() { + mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent() { + Component container = new Service(); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci1 = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci1); + List vfciList = Arrays.asList(vfci1); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfi1 = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + container.setComponentInstances(Arrays.asList(vfi1)); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + List vfciList2 = Arrays.asList(vfci1); + vfNew.setComponentInstances(vfciList2); + + Either eitherComponent = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfi1.getComponentUid())).thenReturn(eitherComponent); + + + Map mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, vfOld, "SRV1.VF2.VFI_1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + assertEquals("SRV1.VF1.VFI_1.VFC1.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent_Proxy() { + Resource container = new Resource(); + container.setComponentType(ComponentTypeEnum.RESOURCE); + container.setResourceType(ResourceTypeEnum.VF); + + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + container.setComponentInstances(Arrays.asList(proxyVfciNew)); + + Map mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, serviceOld, "SRV1.PROXY_VFC_NEW.VFCI1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstanceComponentInstance() { + ComponentInstance oldInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(oldInstance); + + ComponentInstance newInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC2.VFCI_1" ,"SRV1.VF1.VFI_1.VFC2", false); + createVfc(newInstance); + + Map mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, newInstance); + assertEquals("SRV1.VF1.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + @Test + public void testMapOldToNewCapabilitiesOwnerIdsComponentInstComponentInst_Proxy() { + + Component serviceOld = new Service(); + serviceOld.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfOld = new Resource(); + vfOld.setComponentType(ComponentTypeEnum.RESOURCE); + vfOld.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfciOld); + List vfciList = Arrays.asList(vfciOld); + vfOld.setComponentInstances(vfciList); + + ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false); + serviceOld.setComponentInstances(Arrays.asList(vfiOld)); + Either eitherComponent = Either.left(vfOld); + when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent); + + ComponentInstance proxyVfciOld = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + proxyVfciOld.setSourceModelUid("SRV_PROXY"); + Resource proxyVfcOld = new Resource(); + proxyVfcOld.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcOld.setResourceType(ResourceTypeEnum.VFC); + + Either eitherComponent2 = Either.left(serviceOld); + when(toscaOperationFacade.getToscaElement(proxyVfciOld.getSourceModelUid())).thenReturn(eitherComponent2); + + + Component serviceNew = new Service(); + serviceNew.setComponentType(ComponentTypeEnum.SERVICE); + + Resource vfNew = new Resource(); + vfNew.setComponentType(ComponentTypeEnum.RESOURCE); + vfNew.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false); + createVfc(vfciNew); + List vfciList2 = Arrays.asList(vfciNew); + vfNew.setComponentInstances(vfciList2); + + ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false); + serviceNew.setComponentInstances(Arrays.asList(vfiNew)); + Either eitherComponent3 = Either.left(vfNew); + when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3); + + ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true); + proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW"); + Resource proxyVfcNew = new Resource(); + proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE); + proxyVfcNew.setResourceType(ResourceTypeEnum.VFC); + + Either eitherComponent4 = Either.left(serviceNew); + when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4); + + Map mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(proxyVfciOld, proxyVfciNew); + assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1")); + } + + + @Test + public void testConvertToVfciNameMap() { + ComponentInstance componentInstance1 = new ComponentInstance(); + componentInstance1.setName("ComponentInstance1"); + + ComponentInstance componentInstance2 = new ComponentInstance(); + componentInstance2.setName("ComponentInstance2"); + + List componentInstances = Arrays.asList(componentInstance1, componentInstance2); + Map mapResult = mergeInstanceUtils.convertToVfciNameMap(componentInstances); + + assertEquals(2, mapResult.size()); + assertEquals(componentInstance1, mapResult.get("ComponentInstance1")); + assertEquals(componentInstance2, mapResult.get("ComponentInstance2")); + } + + @Test + public void testGetVfcInstances_NullComponentInstance() { + List vfcInstances = mergeInstanceUtils.getVfcInstances(null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Either eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstanceFailedLoadActualComponent() { + ComponentInstance componentInstance = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true); + componentInstance.setSourceModelUid("SRV_PROXY"); + + Either eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND); + when(toscaOperationFacade.getToscaElement(componentInstance.getSourceModelUid())).thenReturn(eitherComponent); + + List vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertTrue(vfcInstances.isEmpty()); + } + + + @Test + public void testGetVfcInstancesAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + + createVfc(componentInstance); + + List vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(1, vfcInstances.size()); + assertEquals(componentInstance, vfcInstances.get(0)); + } + + + @Test + public void testGetVfcInstancesNonAtomicComponentInstance() { + ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false); + + Resource vf = new Resource(); + Either eitherComponent = Either.left(vf); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setResourceType(ResourceTypeEnum.VF); + + ComponentInstance vfci = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false); + createVfc(vfci); + List vfciList = Arrays.asList(vfci); + + vf.setComponentInstances(vfciList); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + + List vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance); + + assertEquals(vfciList, vfcInstances); + } + + @Test + public void testGetVfcInstances_ComponentNullI_nstanceComponent() { + List vfcInstances = mergeInstanceUtils.getVfcInstances(null, new Resource()); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_ComponentInstance_NullComponent() { + List vfcInstances = mergeInstanceUtils.getVfcInstances(new ComponentInstance(), null); + + assertTrue(vfcInstances.isEmpty()); + } + + @Test + public void testGetVfcInstances_NullComponentInstance_NullComponent() { + List vfcInstances = mergeInstanceUtils.getVfcInstances(null, null); + + assertTrue(vfcInstances.isEmpty()); + } + + + /** + * @param uniqueId + * @param componentUid + * @param isProxy + * @return + */ + private ComponentInstance createComponentInstance(String uniqueId, String componentUid, boolean isProxy) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setUniqueId(uniqueId); + componentInstance.setComponentUid(componentUid); + componentInstance.setIsProxy(isProxy); + return componentInstance; + } + + /** + * @param componentInstance + */ + private void createVfc(ComponentInstance componentInstance) { + Resource vfc = new Resource(); + Either eitherComponent = Either.left(vfc); + vfc.setComponentType(ComponentTypeEnum.RESOURCE); + vfc.setResourceType(ResourceTypeEnum.VFC); + when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java new file mode 100644 index 0000000000..44f87bb352 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java @@ -0,0 +1,208 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import fj.data.Either; +import org.junit.Before; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; +import org.openecomp.sdc.be.components.path.beans.TitanGraphTestSetup; +import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class BaseForwardingPathTest extends BeConfDependentTest implements ForwardingPathTestUtils { + + protected User user; + protected ForwardingPathDataDefinition forwardingPathDataDefinition; + + @Autowired + protected TitanGraphClient titanGraphClient; + + @Autowired + protected CapabiltyRequirementConvertor capabiltyRequirementConvertor; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @Autowired + protected ServiceBusinessLogic bl; + + @Autowired + protected IElementOperation elementDao; + + @Autowired + protected ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + + @javax.annotation.Resource + protected TitanDao titanDao; + + @Before + public void initTitan() { + TitanGraphTestSetup.createGraph(titanGraphClient.getGraph().left().value()); + categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(CATEGORY_NAME); + } + + @Before + public void initUser() { + // User data and management + user = new User(); + user.setUserId("jh0003"); + user.setFirstName("Jimmi"); + user.setLastName("Hendrix"); + user.setRole(Role.ADMIN.name()); + } + + + protected CategoryDefinition categoryDefinition; + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + protected static final String CATEGORY_NAME = "cat_name"; + protected static final String FORWARDING_PATH_ID = "forwarding_pathId"; + protected static final String HTTP_PROTOCOL = "http"; + + + protected Resource setupGenericServiceMock() { + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + protected void initGraph() { + Map props = new HashMap<>(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.abstract.nodes.service"); + + GraphTestUtils.createServiceVertex(titanDao, props); + + GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.PNF); + resourceVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "0.1"); + Either vertexTitanOperationStatusEither = titanDao.updateVertex(resourceVertex); + assertTrue(vertexTitanOperationStatusEither.isLeft()); + } + + protected Service createTestService() { + createCategory(); + createServiceCategory(CATEGORY_NAME); + initGraph(); + Service service = new Service(); + service.setName("ForwardingPathTestingService"); + service.setDescription("Just a comment."); + service.setTags(Lists.newArrayList(service.getName(), service.getComponentType().getValue() + service.getName() + "2")); + service.setContactId("as123y"); + service.setIcon("MyIcon"); + service.setProjectCode("414155"); + ArrayList categories = new ArrayList<>(); + CategoryDefinition cd = new CategoryDefinition(); + cd.setName(CATEGORY_NAME); + cd.setNormalizedName("abcde"); + categories.add(cd); + service.setCategories(categories); + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_APPROVED); + return service; + } + + protected void createCategory() { + Either category = elementDao.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory); + assertTrue("Failed to create category", category.isLeft()); + } + + protected void createServiceCategory(String categoryName) { + GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY); + Map metadataProperties = new HashMap<>(); + String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + cat.setUniqueId(catId); + metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, categoryName); + metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + cat.setMetadataProperties(metadataProperties); + cat.updateMetadataJsonWithCurrentMetadataProperties(); + + Either catRes = titanDao.createVertex(cat); + + assertTrue(catRes.isLeft()); + } + + protected Service initForwardPath() { + ForwardingPathDataDefinition forwardingPathDataDefinition = createMockPath(); + Service service = new Service(); + service.setUniqueId(FORWARDING_PATH_ID); + assertEquals(null, service.addForwardingPath(forwardingPathDataDefinition)); + return service; + } + + protected ForwardingPathDataDefinition createMockPath() { + if (forwardingPathDataDefinition != null) { + return forwardingPathDataDefinition; + } + forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo"); + forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString()); + forwardingPathDataDefinition.setDestinationPortNumber("414155"); + forwardingPathDataDefinition.setProtocol(HTTP_PROTOCOL); + org.openecomp.sdc.be.datatypes.elements.ListDataDefinition forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>(); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode", "toNode", "333", "444", "2222", "5555")); + forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode", "toNode2", "4444", "44444", "4", "44")); + forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition); + return forwardingPathDataDefinition; + } + + protected Service createService() { + Either serviceCreateResult = bl.createService(createTestService(), user); + assertTrue("Failed to create service", serviceCreateResult.isLeft()); + Service service = serviceCreateResult.left().value(); +// ComponentInstance componentInstance = new ComponentInstance(); +// componentInstance.setName("Test1"); +// componentInstance.setNormalizedName("Test1"); +// componentInstance.setUniqueId("Test1"); +// componentInstance.setInputValueCounter(1); +// componentInstance.setAttributeValueCounter(1); +// componentInstance.setIcon("network"); +// componentInstance.setComponentVersion("1.0"); +// componentInstance.setIsProxy(true); +// componentInstance.setComponentUid(service.getUniqueId()); +// componentInstance.setPropertyValueCounter(1); +// componentInstance.setPosX("333"); +// componentInstance.setPosY("333"); +// componentInstance.setOriginType(OriginTypeEnum.VF); +// +// Either instanceResult = serviceComponentInstanceBusinessLogic.createComponentInstance("services", service.getUniqueId(), user.getUserId(), componentInstance); +// assertTrue("Failed to create instance", instanceResult.isLeft()); + return service; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java new file mode 100644 index 0000000000..0e56680728 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import org.junit.Before; +import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class BaseForwardingPathVersionChangeTest { + protected Service service; + protected ComponentInstance nodeACI; + protected ComponentInstance newNodeACI; + protected Component newNodeAC; + protected Component newNodeWithoutCapability; + protected DataForMergeHolder dataHolder; + protected static final String nodeA = "nodeA"; + protected static final String NODE_A_FORWARDER_CAPABILITY = "nodeA_FORWARDER_CAPABILITY"; + protected static final String nodeB = "nodeB"; + protected static final String newNodeA = "newNodeA"; + protected static final String fpName = "fpName"; + protected static final String FPId = "1122"; + + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, NODE_A_FORWARDER_CAPABILITY, "nodeBcpType" , "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map forwardingPaths = new HashMap<>(); + forwardingPaths.put(FPId, forwardingPath); + service.setForwardingPaths(forwardingPaths); + nodeACI = new ComponentInstance(); + initComponentInstance(nodeACI, nodeA); + newNodeACI = new ComponentInstance(); + initComponentInstance(newNodeACI, newNodeA); + newNodeAC = new Resource(); + newNodeWithoutCapability=new Resource(); + initComponent(newNodeAC, newNodeA); + service.setComponentInstances(Lists.newArrayList(newNodeACI)); + initComponentWithoutForwarder(newNodeWithoutCapability,"newNodeC"); + service.setComponentInstances(Lists.newArrayList(nodeACI)); + + dataHolder = new DataForMergeHolder(); + dataHolder.setOrigComponentInstId(nodeA); + } + + private void initComponent(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + + private void initComponentWithoutForwarder(Component component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap> capabilities = initCapabilitesWithoutForwarder(); + component.setCapabilities(capabilities); + } + + private HashMap> initCapabilites() { + HashMap> capabilities = new HashMap<>(); + CapabilityDefinition forwarder = new CapabilityDefinition(); + forwarder.setType(ForwardingPathUtils.FORWARDER_CAPABILITY); + forwarder.setUniqueId(NODE_A_FORWARDER_CAPABILITY); + capabilities.put("bla bla", Arrays.asList(forwarder)); + return capabilities; + } + + private HashMap> initCapabilitesWithoutForwarder() { + HashMap> capabilities = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setType("tosca.capabilities.Node"); + capabilityDefinition.setUniqueId("tosca capability"); + capabilities.put("bla bla", Arrays.asList(capabilityDefinition)); + return capabilities; + } + + private void initComponentInstance(ComponentInstance component, String uniqueId) { + component.setUniqueId(uniqueId); + HashMap> capabilities = initCapabilites(); + component.setCapabilities(capabilities); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java new file mode 100644 index 0000000000..03bbc31aef --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java @@ -0,0 +1,107 @@ + +package org.openecomp.sdc.be.components.path; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathBussinessLogicTest extends BaseForwardingPathTest { + + + @Test + public void shouldFailToUpdateForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either serviceResponseFormatEither = bl.updateForwardingPath(FORWARDING_PATH_ID, service, user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldFailToDeleteForwardingPathSincePathDoesNotExist() { + Service service = initForwardPath(); + Either, ResponseFormat> serviceResponseFormatEither = bl.deleteForwardingPaths("delete_forward_test", Sets.newHashSet(FORWARDING_PATH_ID), user, true); + assertEquals(true, serviceResponseFormatEither.isRight()); + } + + @Test + public void shouldSucceedCreateAndDeleteForwardingPath() { + Service createdService = createService(); + Service service = initForwardPath(); + assertNotNull(service); + Either serviceResponseFormatEither = bl.createForwardingPath(createdService.getUniqueId(), service, user, true); + assertEquals(true, serviceResponseFormatEither.isLeft()); + Map forwardingPathsMap = serviceResponseFormatEither.left().value().getForwardingPaths(); + Set pathIds = forwardingPathsMap.keySet(); + assertEquals(1, pathIds.size()); + String toscaResourceName = forwardingPathsMap.values().iterator().next().getToscaResourceName(); + + // should return the created path + Either uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths.keySet().equals(pathIds)); + Map updatedForwardingPaths = new HashMap<>(forwardingPaths); + String newProtocol = "https"; + ForwardingPathDataDefinition forwardingPathDataDefinition = updatedForwardingPaths.values().stream().findAny().get(); + assertEquals(forwardingPathDataDefinition.getProtocol(), HTTP_PROTOCOL); + assertEquals(toscaResourceName, forwardingPathDataDefinition.getToscaResourceName()); + ForwardingPathDataDefinition forwardingPathDataDefinitionUpdate = updatedForwardingPaths.values().iterator().next(); + // updated values + forwardingPathDataDefinitionUpdate.setProtocol(newProtocol); + forwardingPathDataDefinitionUpdate.setPathElements(new ListDataDefinition<>()); + + // should update value + service.getForwardingPaths().clear(); + service.getForwardingPaths().put(forwardingPathDataDefinitionUpdate.getUniqueId(), forwardingPathDataDefinitionUpdate); + serviceResponseFormatEither = bl.updateForwardingPath(createdService.getUniqueId(), service, user, true); + assertTrue(serviceResponseFormatEither.isLeft()); + + // make sure changes were applied + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + Map forwardingPathsUpdated = uiServiceDataTransfer.getForwardingPaths(); + ForwardingPathDataDefinition updatedData = forwardingPathsUpdated.values().iterator().next(); + assertEquals(newProtocol, updatedData.getProtocol()); + assertTrue(updatedData.getPathElements().isEmpty()); + + Service createdData = serviceResponseFormatEither.left().value(); + Set paths = createdData.getForwardingPaths().keySet(); + Either, ResponseFormat> setResponseFormatEither = bl.deleteForwardingPaths(createdService.getUniqueId(), paths, user, true); + assertEquals(true, setResponseFormatEither.isLeft()); + + // nothing to return now + uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.COMPONENT_INSTANCES.getValue(),ComponentFieldsEnum.FORWARDING_PATHS.getValue())); + assertEquals(true, uiResaponse.isLeft()); + uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value(); + forwardingPaths = uiServiceDataTransfer.getForwardingPaths(); + assertTrue(forwardingPaths == null || forwardingPaths.isEmpty()); + + } + + + + +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java new file mode 100644 index 0000000000..5af94d7938 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.be.components.path; + +import org.javatuples.Pair; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +public class ForwardingPathChangeVersionTest extends BaseForwardingPathVersionChangeTest { + + + @Test + public void updateForwardingPath() { + Pair, Map> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(1, updated.size()); + assertEquals(newNodeA, updated.values().iterator().next().getPathElements().getListToscaDataDefinition().get(0).getFromNode()); + Map deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(0, deleted.size()); + } + + @Test + public void deleteForwardingPath(){ + newNodeAC.setCapabilities(new HashMap<>()); + Pair, Map> pair = new ForwardingPathUtils() + .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA); + Map updated = pair.getValue0(); + assertNotNull(updated); + assertEquals(0, updated.size()); + + Map deleted = pair.getValue1(); + assertNotNull(deleted); + assertEquals(1, deleted.size()); + assertEquals(FPId, deleted.keySet().stream().findAny().get()); + } + + @Test + public void fetchPathsToBeDeletedZeroPaths(){ + Set data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeAC); + assertEquals(0,data.size()); + } + + @Test + public void fetchPathsToBeDeleted(){ + Set data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service, + dataHolder,newNodeWithoutCapability); + assertEquals(1,data.size()); + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java new file mode 100644 index 0000000000..e5de493cb1 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class ForwardingPathDeleteCITest { + + private Service service; + private static final String nodeA = "nodeA"; + private static final String nodeB = "nodeB"; + private static final String fpName = "fpName"; + + @Before + public void initService() { + service = new Service(); + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName); + String protocol = "protocol"; + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber("DestinationPortNumber"); + ListDataDefinition forwardingPathElementListDataDefinition + = new ListDataDefinition<>(); + + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeA, nodeB, "nodeAcpType", "nodeBcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition(nodeB, "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPathElementListDataDefinition.add( + new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", + "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + Map forwardingPaths = new HashMap<>(); + forwardingPaths.put("NEW", forwardingPath); + service.setForwardingPaths(forwardingPaths); + } + + + @Test + public void getListToDelete() { + + Set forwardingPathNamesToDeleteOnComponenetInstanceDeletion = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeA); + assertEquals(1, forwardingPathNamesToDeleteOnComponenetInstanceDeletion.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + Set forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeB); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(1, forwardingPathNamesToDeleteOnCIDelete.size()); + assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName)); + + forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils() + .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, "Does not exist"); + assertNotNull(forwardingPathNamesToDeleteOnCIDelete); + assertEquals(0, forwardingPathNamesToDeleteOnCIDelete.size()); + assertFalse(forwardingPathNamesToDeleteOnCIDelete.contains(fpName)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java new file mode 100644 index 0000000000..9ab9ffd788 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.be.components.path; + +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; + +public interface ForwardingPathTestUtils { + + default ForwardingPathDataDefinition createPath(String pathName, String protocol, String ports, String uniqueId){ + ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName); + forwardingPath.setProtocol(protocol); + forwardingPath.setDestinationPortNumber(ports); + forwardingPath.setUniqueId(uniqueId); + ListDataDefinition forwardingPathElementListDataDefinition = new ListDataDefinition<>(); + String nodeA = "nodeA"; + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName")); + forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName")); + forwardingPath.setPathElements(forwardingPathElementListDataDefinition); + + return forwardingPath; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java new file mode 100644 index 0000000000..e7100a4a7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java @@ -0,0 +1,186 @@ +package org.openecomp.sdc.be.components.path; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDER; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PORTS_RANGE; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PROTOCOL; +import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.addForwardingPaths; + +/** + * @author KATYR, ORENK + * @since November 19, 2017 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/paths/path-context.xml") +public class ForwardingPathToscaUtilTest extends BaseForwardingPathTest { + + private static final String NODE_NAME_1 = "nodeA-name"; + private static final String NODE_NAME_2 = "nodeB-name"; + private static final String PATH_1_PROTOCOL = "protocol-path1"; + private static final String PATH_1_DESC = "path1-desc"; + private static final String PATH_1_PORTS = "8585"; + private static final String PATH_1_NAME = "pathName1"; + private Service service; + private Map originComponents = new HashMap<>(); + private static final String NODE_ID_1 = "nodeA-id"; + private static final String NODE_ID_2 = "nodeB-id"; + private static final String FORWARDING_PATH_TOSCA_TYPE = "org.openecomp.nodes.ForwardingPath"; + + + @Before + public void setUpForwardingPath() { + service = initForwardPath(); + List componentInstances = new ArrayList<>(); + componentInstances.add(generateComponentInstance(NODE_NAME_1, NODE_ID_1)); + componentInstances.add(generateComponentInstance(NODE_NAME_2, NODE_ID_2)); + service.setComponentInstances(componentInstances); + } + + private ComponentInstance generateComponentInstance(String name, String uuid) { + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setName(name); + componentInstance.setUniqueId(uuid); + componentInstance.setComponentUid(uuid); + Map> capabiltiesMap = new HashMap<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setMinOccurrences(Integer.toString(1)); + capabilityDefinition.setMaxOccurrences(Integer.toString(100)); + capabilityDefinition.setType(ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME); + capabilityDefinition.setName(name); + capabilityDefinition.setUniqueId(name); + capabilityDefinition.setPath(Arrays.asList("Just", "something", "to", "read")); + capabiltiesMap.put(capabilityDefinition.getName(), + Collections.singletonList(capabilityDefinition)); + componentInstance.setCapabilities(capabiltiesMap); + Resource resource = new Resource(); + resource.setToscaResourceName("test"); + originComponents.put(uuid, resource); + return componentInstance; + } + + + @Test + public void singleElementPath() { + createPathSingleElement(); + Map nodeTemplatesRes = new HashMap<>(); + + Map expectedNodeTemplatesRes = new HashMap<>(); + ToscaNodeTemplate pathEntry = new ToscaNodeTemplate(); + pathEntry.setType(FORWARDING_PATH_TOSCA_TYPE); + Map expectedProps = new HashMap<>(); + expectedProps.put(PORTS_RANGE, Collections.singletonList(PATH_1_PORTS)); + expectedProps.put(PROTOCOL, PATH_1_PROTOCOL); + pathEntry.setProperties(expectedProps); + List> requirements = new ArrayList<>(); + ToscaTemplateRequirement firstEntryReq = new ToscaTemplateRequirement(); + ToscaTemplateRequirement secondEntryReq = new ToscaTemplateRequirement(); + + firstEntryReq.setCapability("null." + NODE_NAME_1); + secondEntryReq.setCapability("null." + NODE_NAME_2); + + firstEntryReq.setNode(NODE_NAME_1); + secondEntryReq.setNode(NODE_NAME_2); + + firstEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + secondEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME); + + Map entryMap1 = new HashMap<>(); + Map entryMap2 = new HashMap<>(); + + entryMap1.put(FORWARDER, firstEntryReq); + entryMap2.put(FORWARDER, secondEntryReq); + + requirements.add(entryMap1); + requirements.add(entryMap2); + + pathEntry.setRequirements(requirements); + expectedNodeTemplatesRes.put(PATH_1_NAME, pathEntry); + addForwardingPaths(service, nodeTemplatesRes, capabiltyRequirementConvertor, originComponents, + toscaOperationFacade); + + assertEquals(2, nodeTemplatesRes.get(PATH_1_NAME).getRequirements().size()); + compareToscaPathEntry(expectedNodeTemplatesRes, nodeTemplatesRes); + } + + private void compareToscaPathEntry(Map expectedNodeTemplatesRes, + Map nodeTemplatesRes) { + final ToscaNodeTemplate expectedTemplate = expectedNodeTemplatesRes.get(PATH_1_NAME); + final ToscaNodeTemplate actualTemplate = nodeTemplatesRes.get(PATH_1_NAME); + assertEquals(expectedTemplate.getProperties(), actualTemplate.getProperties()); + final int size = expectedTemplate.getRequirements().size(); + assertEquals(size, + actualTemplate.getRequirements().size()); + for (int i = 0; i < size; i++) { + compareToscaRequirement(expectedTemplate, actualTemplate, i); + } + } + + private void compareToscaRequirement(ToscaNodeTemplate expectedTemplate, + ToscaNodeTemplate actualTemplate, + int i) { + final ToscaTemplateRequirement actualRequirement = + actualTemplate.getRequirements().get(i).get(FORWARDER); + final ToscaTemplateRequirement expectedToscaRequirement = expectedTemplate + .getRequirements() + .get(i).get(FORWARDER); + assertEquals(actualRequirement.getCapability(), expectedToscaRequirement.getCapability()); + assertEquals(actualRequirement.getNode(), expectedToscaRequirement.getNode()); + } + + private void createPathSingleElement() { + ForwardingPathElementDataDefinition element1 = initElement(NODE_ID_1, NODE_ID_2, NODE_NAME_1, + NODE_NAME_2); + + ListDataDefinition list = new ListDataDefinition<>(); + list.add(element1); + + + ForwardingPathDataDefinition path = new ForwardingPathDataDefinition(); + path.setDescription(PATH_1_DESC); + path.setProtocol(PATH_1_PROTOCOL); + path.setDestinationPortNumber(PATH_1_PORTS); + path.setToscaResourceName(FORWARDING_PATH_TOSCA_TYPE); + path.setPathElements(list); + path.setName(PATH_1_NAME); + + Map paths = new HashMap<>(); + paths.put(PATH_1_NAME, path); + + service.setForwardingPaths(paths); + } + + private ForwardingPathElementDataDefinition initElement(String fromId, String toId, String + fromCP, String toCP) { + ForwardingPathElementDataDefinition element = new ForwardingPathElementDataDefinition(); + element.setFromCP(fromCP); + element.setFromNode(fromId); + element.setToCP(toCP); + element.setToNode(toId); + return element; + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java new file mode 100644 index 0000000000..fd9e25f475 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java @@ -0,0 +1,151 @@ +package org.openecomp.sdc.be.components.path; + + +import com.google.common.collect.Sets; +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; +import java.util.Set; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +public class ForwardingPathValidatorTest implements ForwardingPathTestUtils { + + ResponseFormatManager mock; + + private Service service = (Service) getToscaFullElement().left().value(); + + + @Mock + ToscaOperationFacade toscaOperationFacade; + @InjectMocks + ForwardingPathValidationUtilTest test = new ForwardingPathValidationUtilTest(); + + private static final String SERVICE_ID = "serviceid1"; + + + + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + mock = Mockito.mock(ResponseFormatManager.class); + when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class))).thenReturn(Either.left(service)); + when(mock.getResponseFormat(any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any())).thenReturn(new ResponseFormat()); + when(mock.getResponseFormat(any(), any(), any())).thenReturn(new ResponseFormat()); + + } + + @Test + public void testValidForwardingPathName(){ + + Collection paths = createData("pathName", "http", "8285", "pathName"); + Either booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isLeft()); + } + + @Test + public void testEmptyForwardingPathName(){ + Collection paths = createData("", "protocol", "8285", "name1"); + Either booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + } + + @Test + public void testLongForwardingPathName(){ + String pathName = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection paths = createData(pathName, + "http", "port", "name1"); + Either booleanResponseFormatEither = test + .validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testUniqueForwardingPathNameUpdateName(){ + + Collection paths = createData("pathName4", "httpfd", "82df85", "name1"); + Either booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testUniqueForwardingPathNameUpdatePort(){ + + Collection paths = createData("pathName3", "httpfd", "82df85", "name1"); + Either booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true); + assertTrue(booleanResponseFormatEither.isLeft()); + + } + + @Test + public void testLongForwardingPathPortNumber(){ + String port = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection paths = createData("pathName", + "http", port, "name1"); + Either booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + @Test + public void testLongForwardingPathProtocol(){ + String protocol = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" + + "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" + + "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: "; + Collection paths = createData("pathName", + protocol, "port", "name1"); + Either booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false); + assertTrue(booleanResponseFormatEither.isRight()); + + } + + private Set createData(String pathName, String protocol, String ports, String uniqueId) { + + return Sets.newHashSet(createPath(pathName, protocol, ports, uniqueId)); + } + + + private Either getToscaFullElement() { + + return Either.left((T) setUpServiceMcok()); + } + + private Service setUpServiceMcok(){ + Service service = new Service(); + service.addForwardingPath(createPath("pathName3", "http", "8285", "name1")); + return service; + } + + private class ForwardingPathValidationUtilTest extends ForwardingPathValidator { + + protected ResponseFormatManager getResponseFormatManager() { + return mock; + } + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java new file mode 100644 index 0000000000..290ba07883 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("artifact-cassandra-dao") +public class ArtifactCassandraDaoMock extends ArtifactCassandraDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java new file mode 100644 index 0000000000..c4885e1f07 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("audit-cassandra-dao") +public class AuditCassandraDaoMock extends AuditCassandraDao{ + + @PostConstruct + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java new file mode 100644 index 0000000000..0d4b2f1e7e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.cassandra.CassandraClient; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.springframework.stereotype.Component; + +@Component("cassandra-client") +public class CassandraClientMock extends CassandraClient{ + public CassandraClientMock() { + + } + + @Override + public Either, CassandraOperationStatus> connect(String keyspace) { + return null; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java new file mode 100644 index 0000000000..6a9731e86d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.ComponentCacheAccessor; +import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao; +import org.openecomp.sdc.be.resources.data.ComponentCacheData; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component("component-cassandra-dao") +public class ComponentCassandraDaoMock extends ComponentCassandraDao { + + public static Integer DEFAULT_FETCH_SIZE = 500; + private ComponentCacheAccessor componentCacheAccessor; + + public ComponentCassandraDaoMock() { + super(); + } + + @PostConstruct + public void init() { + + } + + public Either, ActionStatus> getComponents(List ids) { + + return null; + } + + public Either, ActionStatus> getAllComponentIdTimeAndType() { + return null; + } + + + public Either getComponent(String id) { + + return null; + } + + public CassandraOperationStatus saveComponent(ComponentCacheData componentCacheData) { + return null; + } + + + public Either isTableEmpty(String tableName) { + return null; + } + + + public Either, Set>, ActionStatus> getComponents( + Map idToTimestampMap) { + + return null; + } + + public CassandraOperationStatus deleteComponent(String id) { + return null; + } + + } + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java new file mode 100644 index 0000000000..748ae56bd7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java @@ -0,0 +1,61 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +public class DistributionEngineMock implements IDistributionEngine { + @Override + public boolean isActive() { + return false; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) { + return null; + } + + @Override + public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable(String envName) { + return null; + } + + @Override + public StorageOperationStatus isEnvironmentAvailable() { + return null; + } + + @Override + public void disableEnvironment(String envName) { + + } + + @Override + public StorageOperationStatus isReadyForDistribution(Service service, String envName) { + return null; + } + + @Override + public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) { + return null; + } + + @Override + public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) { + return null; + } + + @Override + public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) { + return null; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java new file mode 100644 index 0000000000..2d7b1ad287 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("operational-environment-dao") +public class EnvironmentCassandraDaoMock extends OperationalEnvironmentDao { + @PostConstruct + @Override + public void init() { + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java new file mode 100644 index 0000000000..09e1a72b44 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.impl.ForwardingPathUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +@org.springframework.stereotype.Component("tosca-operation-facade") +public class ForwardingPathToscaOperationFacade extends ToscaOperationFacade { + protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service"; + @Override + public Either getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return Either.left(setupGenericServiceMock()); + } + + protected Resource setupGenericServiceMock(){ + Resource genericService = new Resource(); + genericService.setVersion("1.0"); + genericService.setToscaResourceName(GENERIC_SERVICE_NAME); + return genericService; + } + + @Override + public Either getLatestByName(String resourceName) { + if(resourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || resourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByName(resourceName); + } + + @Override + public Either getLatestByToscaResourceName(String toscaResourceName) { + if(toscaResourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || toscaResourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){ + Resource component = new Resource(); + component.setToscaResourceName(GENERIC_SERVICE_NAME); + return Either.left((T)component); + } + return super.getLatestByToscaResourceName(toscaResourceName); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java new file mode 100644 index 0000000000..1aa3ab8102 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.be.components.path.beans; + +import fj.data.Either; +import org.openecomp.sdc.be.components.path.ForwardingPathValidator; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.exception.ResponseFormat; + +import java.util.Collection; + +public class ForwardingPathValidatorMock extends ForwardingPathValidator { + @Override + public Either validateForwardingPaths(Collection paths, String serviceId, + boolean isUpdate) { + return Either.left(Boolean.TRUE); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java new file mode 100644 index 0000000000..4e3923d2ea --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java @@ -0,0 +1,218 @@ +package org.openecomp.sdc.be.components.path.beans; + + +import com.thinkaurelius.titan.core.InvalidElementException; +import com.thinkaurelius.titan.core.InvalidIDException; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.QueryException; +import com.thinkaurelius.titan.core.SchemaViolationException; +import com.thinkaurelius.titan.core.TitanConfigurationException; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import com.thinkaurelius.titan.core.util.TitanCleanup; +import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException; +import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; +import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.HashMap; + +@Component("titan-client") +public class InMemoryTitanGraphClient extends TitanGraphClient { + + + private static final Logger logger = LoggerFactory.getLogger(InMemoryTitanGraphClient.class); + + private static final String OK = "GOOD"; + + public InMemoryTitanGraphClient() { + } + + + private TitanGraph graph; + TitanClientStrategy titanClientStrategy; + + public InMemoryTitanGraphClient(TitanClientStrategy titanClientStrategy) { + super(); + this.titanClientStrategy = titanClientStrategy; + logger.info("** TitanGraphClient created"); + } + + @PostConstruct + public TitanOperationStatus createGraph() { + + logger.info("** createGraph started **"); + graph = TitanFactory.build().set("storage.backend", "inmemory").open(); + createTitanSchema(); + + logger.info("** in memory graph created"); + return TitanOperationStatus.OK; + + } + + + public void cleanupGraph() { + if (graph != null) { + // graph.shutdown(); + graph.close(); + TitanCleanup.clear(graph); + } + } + + public TitanOperationStatus createGraph(String titanCfgFile) { + logger.info("** open graph with {} started", titanCfgFile); + try { + logger.info("openGraph : try to load file {}", titanCfgFile); + graph = TitanFactory.open(titanCfgFile); + if (graph.isClosed()) { + logger.error("titan graph was not initialized"); + return TitanOperationStatus.NOT_CREATED; + } + + } catch (Exception e) { + this.graph = null; + logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e); + return TitanOperationStatus.NOT_CONNECTED; + } + + logger.info("** Titan graph created "); + + return TitanOperationStatus.OK; + } + + + public Either getGraph() { + if (graph != null) { + return Either.left(graph); + } else { + return Either.right(TitanOperationStatus.NOT_CREATED); + } + } + + public TitanOperationStatus commit() { + if (graph != null) { + try { + graph.tx().commit(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public TitanOperationStatus rollback() { + if (graph != null) { + try { + // graph.rollback(); + graph.tx().rollback(); + return TitanOperationStatus.OK; + } catch (Exception e) { + return handleTitanException(e); + } + } else { + return TitanOperationStatus.NOT_CREATED; + } + } + + public static TitanOperationStatus handleTitanException(Exception e) { + if (e instanceof TitanConfigurationException) { + return TitanOperationStatus.TITAN_CONFIGURATION; + } + if (e instanceof SchemaViolationException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof PermanentLockingException) { + return TitanOperationStatus.TITAN_SCHEMA_VIOLATION; + } + if (e instanceof IDPoolExhaustedException) { + return TitanOperationStatus.GENERAL_ERROR; + } + if (e instanceof InvalidElementException) { + return TitanOperationStatus.INVALID_ELEMENT; + } + if (e instanceof InvalidIDException) { + return TitanOperationStatus.INVALID_ID; + } + if (e instanceof QueryException) { + return TitanOperationStatus.INVALID_QUERY; + } + if (e instanceof ResourceUnavailableException) { + return TitanOperationStatus.RESOURCE_UNAVAILABLE; + } + if (e instanceof IllegalArgumentException) { + // TODO check the error message?? + return TitanOperationStatus.ILLEGAL_ARGUMENT; + } + + return TitanOperationStatus.GENERAL_ERROR; + } + + public boolean getHealth() { + return true; + } + + private boolean isGraphOpen() { + return true; + } + + + private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck"; + + + private void createTitanSchema() { + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java new file mode 100644 index 0000000000..4e0105f067 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.components.path.beans; + +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +@Component("sdc-schema-files-cassandra-dao") +public class SdcSchemaFilesCassandraDaoMock extends SdcSchemaFilesCassandraDao { + + @PostConstruct + @Override + public void init() { + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java new file mode 100644 index 0000000000..7a7eff879a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java @@ -0,0 +1,166 @@ +package org.openecomp.sdc.be.components.path.beans; + +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanGraphQuery; +import com.thinkaurelius.titan.core.schema.ConsistencyModifier; +import com.thinkaurelius.titan.core.schema.TitanGraphIndex; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class TitanGraphTestSetup { + + + private static final Logger logger = LoggerFactory.getLogger(TitanGraphTestSetup.class); + + private static TitanGraph graph; + + public static boolean createGraph( TitanGraph graph) { + TitanGraphTestSetup.graph = graph; + createIndexesAndDefaults(); + + logger.info("** Titan graph created "); + + return true; + } + + private static boolean isVertexExist(Map properties) { + TitanGraphQuery query = graph.query(); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry entry : properties.entrySet()) { + query = query.has(entry.getKey(), entry.getValue()); + } + } + Iterable vertecies = query.vertices(); + java.util.Iterator iterator = vertecies.iterator(); + if (iterator.hasNext()) { + return true; + } + return false; + } + + private static void createDefaultAdminUser() { + createUser(getDefaultUserAdmin()); + graph.tx().commit(); + + } + + private static void createUser(UserData user) { + Map checkedProperties = new HashMap<>(); + checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId()); + checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + Map properties = null; + if (!isVertexExist(checkedProperties)) { + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()); + properties = user.toGraphMap(); + for (Map.Entry entry : properties.entrySet()) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private static UserData getDefaultUserAdmin() { + UserData userData = new UserData(); + userData.setAction(ActionEnum.Create); + userData.setElementType(GraphElementTypeEnum.Node); + userData.setUserId("jh0003"); + userData.setEmail("admin@sdc.com"); + userData.setFirstName("Jimmy"); + userData.setLastName("Hendrix"); + userData.setRole("ADMIN"); + userData.setStatus(UserStatusEnum.ACTIVE.name()); + userData.setLastLoginTime(0L); + return userData; + } + + + private static void createVertexIndixes() { + logger.info("** createVertexIndixes started"); + + TitanManagement graphMgt = graph.openManagement(); + TitanGraphIndex index = null; + for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) { + PropertyKey propKey = null; + if (!graphMgt.containsPropertyKey(prop.getProperty())) { + Class clazz = prop.getClazz(); + if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) { + propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + } + } else { + propKey = graphMgt.getPropertyKey(prop.getProperty()); + } + if (prop.isIndexed()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + if (prop.isUnique()) { + index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex(); + + graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures + // only + // one + // name + // per + // vertex + graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures + // name + // uniqueness + // in + // the + // graph + + } else { + graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex(); + } + } + } + } + graphMgt.commit(); + logger.info("** createVertexIndixes ended"); + + } + + private static void createEdgeIndixes() { + logger.info("** createEdgeIndixes started"); + TitanManagement graphMgt = graph.openManagement(); + for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) { + if (!graphMgt.containsGraphIndex(prop.getProperty())) { + PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make(); + graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex(); + + } + } + graphMgt.commit(); + logger.info("** createEdgeIndixes ended"); + } + + private static void createIndexesAndDefaults() { + createVertexIndixes(); + createEdgeIndixes(); + createDefaultAdminUser(); + createRootCatalogVertex(); + } + private static void createRootCatalogVertex(){ + Vertex vertex = graph.addVertex(); + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId()); + vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()); + graph.tx().commit(); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java new file mode 100644 index 0000000000..79a1dab517 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.components.path.utils; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +public final class GraphTestUtils { + + public static GraphVertex createResourceVertex(TitanDao titanDao, Map metadataProps, ResourceTypeEnum type) { + GraphVertex vertex = new GraphVertex(); + if (type == ResourceTypeEnum.VF) { + vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + } else { + vertex.setLabel(VertexTypeEnum.NODE_TYPE); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE); + } + String uuid = UUID.randomUUID().toString(); + vertex.setUniqueId(uuid); + + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name()); + vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static GraphVertex createServiceVertex(TitanDao titanDao, Map metadataProps){ + GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE); + String uuid = UUID.randomUUID().toString(); + + vertex.setUniqueId(uuid); + vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE); + vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid); + vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + for (Map.Entry prop : metadataProps.entrySet()) { + vertex.addMetadataProperty(prop.getKey(), prop.getValue()); + } + titanDao.createVertex(vertex); + titanDao.commit(); + return vertex; + } + + public static void clearGraph(TitanDao titanDao) { + Either graphResult = titanDao.getGraph(); + TitanGraph graph = graphResult.left().value(); + + Iterable vertices = graph.query().vertices(); + if (vertices != null) { + Iterator iterator = vertices.iterator(); + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + vertex.remove(); + } + } + titanDao.commit(); + } + + public static String exportGraphMl(TitanGraph graph, String outputDirectory) { + String result = null; + String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml"; + try { + try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) { + graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph); + } + result = outputFile; + graph.tx().commit(); + } catch (Exception e) { + graph.tx().rollback(); + e.printStackTrace(); + } + return result; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java new file mode 100644 index 0000000000..9bd04d6da3 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java @@ -0,0 +1,238 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +public class ComponentInstancePropertyDeceleratorTest extends PropertyDeceleratorTestBase { + + private static final String INSTANCE_ID = "inst1"; + private static final String RESOURCE_ID = "resource1"; + + @InjectMocks + private ComponentInstancePropertyDecelerator testInstance; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Captor + private ArgumentCaptor>> instancePropertiesCaptor; + private Resource resource; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithInstance(); + } + + @Test + public void declarePropertiesAsInputs_componentInstanceNotExist() { + Component cmpt = new Resource(); + Either, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(cmpt, "someCmptInstId", Collections.emptyList()); + assertThat(createdInputs.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(toscaOperationFacade); + } + + @Test + public void declarePropertiesAsInputs_singleNonComplexProperty() { + List properties = Collections.singletonList(prop1); + List propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + List inputs = createdInputs.left().value(); + List capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_multipleNonComplexProperty() { + List properties = Arrays.asList(prop1, prop2); + List propsToDeclare = createInstancePropInputList(properties); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List inputs = createdInputs.left().value(); + List capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + verifyCreatedInputs(properties, capturedInstanceProperties, inputs); + verifyUpdatedProperties(properties, capturedInstanceProperties, inputs); + } + + @Test + public void declarePropertiesAsInputs_singleComplexProperty() { + PropertyDefinition innerProp1 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP1) + .setValue("true") + .setType("boolean") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + PropertyDefinition innerProp2 = new PropertyDataDefinitionBuilder() + .setName(INNER_PROP2) + .setValue("abc") + .setType("string") + .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming") + .build(); + List propsToDeclare = createComplexPropInputList(innerProp1, innerProp2); + when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap())); + Either, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare); + + List inputs = createdInputs.left().value(); + List capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID); + + verifyCreatedInputsFromComplexProperty(propsToDeclare, capturedInstanceProperties, inputs); + verifyUpdatedComplexProperty(capturedInstanceProperties, inputs); + } + + private void verifyUpdatedProperties(List properties, List capturedInstanceProperties, List inputs) { + assertThat(capturedInstanceProperties).hasSize(properties.size()); + Map updatedPropertiesByName = MapUtil.toMap(capturedInstanceProperties, ComponentInstanceProperty::getName); + properties.forEach(prop -> verifyUpdatedInstanceProperty(prop, updatedPropertiesByName.get(prop.getName()), inputs)); + } + + private void verifyUpdatedComplexProperty(List capturedInstanceProperties, List inputs) { + assertThat(capturedInstanceProperties).hasSize(1); + verifyUpdatedInstanceComplexProperty(capturedInstanceProperties.get(0), inputs); + } + + private void verifyCreatedInputs(List originalPropsToDeclare, List capturedUpdatedProperties, List inputs) { + assertThat(inputs).hasSize(originalPropsToDeclare.size()); + Map propertyIdToCreatedInput = MapUtil.toMap(inputs, InputDefinition::getPropertyId); + originalPropsToDeclare.forEach(propToDeclare -> verifyCreatedInput(propToDeclare, propertyIdToCreatedInput.get(propToDeclare.getUniqueId()))); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyCreatedInputsFromComplexProperty(List propsToDeclare, List capturedInstanceProperties, List inputs) { + assertThat(inputs).hasSize(propsToDeclare.size()); + Map inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + propsToDeclare.forEach(propToDeclare -> verifyCreatedInputFromComplexProperty(propToDeclare, inputsByName)); + Map> propertyIdToCreatedInput = MapUtil.groupListBy(inputs, InputDefinition::getPropertyId); + capturedInstanceProperties.forEach(updatedProperty -> verifyInputPropertiesListFromComplexProperty(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + private void verifyInputPropertiesListFromComplexProperty(ComponentInstanceProperty updatedProperty, List inputs) { + inputs.forEach(input -> verifyInputPropertiesList(updatedProperty, input)); + } + + private void verifyCreatedInputFromComplexProperty(ComponentInstancePropInput parentProperty, Map inputsByName) { + PropertyDefinition innerProperty = parentProperty.getInput(); + String expectedInputName = generateExpectedInputName(parentProperty, innerProperty); + InputDefinition input = inputsByName.get(expectedInputName); + assertThat(input.getType()).isEqualTo(innerProperty.getType()); + assertThat(input.getValue()).isEqualTo(innerProperty.getValue()); +// assertThat(input.getDefaultValue()).isEqualTo(innerProperty.getValue());//bug + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(parentProperty.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + + } + + private void verifyInputPropertiesList(ComponentInstanceProperty updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(updatedProperty).isEqualTo(input.getProperties().get(0)); + } + + + private List createComplexPropInputList(PropertyDefinition ... innerProperties) { + return Stream.of(innerProperties).map(this::createComplexPropInput).collect(Collectors.toList()); + } + + private ComponentInstancePropInput createComplexPropInput(PropertyDefinition innerProp) { + ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput(new ComponentInstanceProperty(complexProperty)); + componentInstancePropInput.setInput(innerProp); + componentInstancePropInput.setPropertiesName(complexProperty.getName() + "#" + innerProp.getName()); + return componentInstancePropInput; + } + + private void verifyUpdatedInstanceProperty(PropertyDataDefinition originalProperty, ComponentInstanceProperty updatedProperty, List inputs) { + assertThat(updatedProperty.getValue()).isEqualTo(generateGetInputValue(generateExpectedInputName(originalProperty))); + assertThat(updatedProperty.isGetInputProperty()).isTrue(); + assertThat(updatedProperty.getName()).isEqualTo(originalProperty.getName()); + List getInputValues = updatedProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyUpdatedInstanceComplexProperty(ComponentInstanceProperty updatedComplexProperty, List inputs) { + assertThat(updatedComplexProperty.getValue()).isEqualTo(generateComplexGetInputValue(inputs)); + assertThat(updatedComplexProperty.isGetInputProperty()).isTrue(); + assertThat(updatedComplexProperty.getName()).isEqualTo(complexProperty.getName()); + List getInputValues = updatedComplexProperty.getGetInputValues(); + verifyGetInputValues(getInputValues, inputs); + } + + private void verifyGetInputValues(List getInputValues, List inputs) { + Map inputsByName = MapUtil.toMap(inputs, InputDefinition::getName); + getInputValues.forEach(getInputVal -> { + InputDefinition input = inputsByName.get(getInputVal.getInputName()); + assertThat(input.getUniqueId()).isEqualTo(getInputVal.getInputId()); + }); + } + + private String generateComplexGetInputValue(List createdInputs) { + return String.format("{\"%s\":%s,\"%s\":%s}", INNER_PROP1, generateGetInputValue(createdInputs.get(0).getName()), INNER_PROP2, generateGetInputValue(createdInputs.get(1).getName())); + } + + private String generateExpectedInputName(PropertyDataDefinition prop) { + return INSTANCE_ID + "_" + prop.getName(); + } + + private String generateExpectedInputName(PropertyDefinition parentProp, PropertyDefinition innerProperty) { + return INSTANCE_ID + "_" + parentProp.getName()+ "_" + innerProperty.getName(); + } + + private void verifyCreatedInput(PropertyDataDefinition property, InputDefinition input) { + assertThat(input.getType()).isEqualTo(property.getType()); + assertThat(input.getName()).isEqualTo(generateExpectedInputName(property)); + assertThat(input.getValue()).isEqualTo(property.getValue()); + assertThat(input.getDefaultValue()).isEqualTo(property.getValue()); + assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName())); + assertThat(input.getPropertyId()).isEqualTo(property.getUniqueId()); + assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID); + } + + private Resource createResourceWithInstance() { + ComponentInstance inst1 = new ComponentInstanceBuilder() + .setId(INSTANCE_ID) + .setNormalizedName(INSTANCE_ID) + .build(); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .addComponentInstance(inst1) + .build(); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java new file mode 100644 index 0000000000..cd454d5a84 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java @@ -0,0 +1,172 @@ +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + + +@RunWith(MockitoJUnitRunner.class) +//note that testing for most of the common logic is under the ComponentInstancePropertyDeceleratorTest +public class PolicyPropertyDeceleratorTest extends PropertyDeceleratorTestBase{ + + private static final String POLICY_ID = "policyId"; + private static final String RESOURCE_ID = "resourceId"; + private static final String INPUT_ID = "inputId"; + @InjectMocks + private PolicyPropertyDecelerator policyPropertyDecelerator; + @Mock + private PolicyOperation policyOperation; + @Mock + private PropertyOperation propertyOperation; + @Captor + private ArgumentCaptor> updatedPropsCapture; + private Resource resource; + private InputDefinition input; + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + resource = createResourceWithPolicy(); + input = new InputDefinition(); + input.setUniqueId(INPUT_ID); + input.setName(INPUT_ID); + input.setValue("value"); + } + + @Test + public void testDeclarePropertiesAsInputs_policyNotExist() { + Either, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, "nonExistingPolicy", Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testDeclarePropertiesAsInputs_failedToUpdateProperties() { + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + Either, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, Collections.emptyList()); + assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testDeclarePropertiesAsInputs() { + List properties = Arrays.asList(prop1, prop2); + List propsToDeclare = createInstancePropInputList(properties); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + Either, StorageOperationStatus> createdInputs = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, propsToDeclare); + List inputs = createdInputs.left().value(); + assertThat(inputs).hasSize(2); + verifyInputPropertiesList(inputs, updatedPropsCapture.getValue()); + //creation of inputs values is part of the DefaultPropertyDecelerator and is tested in the ComponentInstancePropertyDeceleratorTest class + } + + @Test + public void testUnDeclareProperties_whenComponentHasNoPolicies_returnOk() { + Resource resource = new Resource(); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void testUnDeclareProperties_whenNoPropertiesFromPolicyMatchInputId_returnOk() { + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(createResourceWithPolicy(), input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + verifyZeroInteractions(policyOperation); + } + + @Test + public void whenFailingToUpdateDeclaredProperties_returnErrorStatus() { + Resource resource = createResourceWithPolicies(POLICY_ID); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + policyDefinition.setProperties(Collections.singletonList(getInputPropForInput)); + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR); + } + + @Test + public void testUnDeclareProperties_propertiesUpdatedCorrectly() { + Resource resource = createResourceWithPolicies(POLICY_ID, "policyId2"); + PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID); + PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID); + PropertyDataDefinition someOtherProperty = new PropertyDataDefinitionBuilder().build(); + policyDefinition.setProperties(Arrays.asList(getInputPropForInput, someOtherProperty)); + + when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue())); + when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK); + StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input); + + assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK); + List updatedProperties = updatedPropsCapture.getValue(); + assertThat(updatedProperties).hasSize(1); + PropertyDataDefinition updatedProperty = updatedProperties.get(0); + assertThat(updatedProperty.isGetInputProperty()).isFalse(); + assertThat(updatedProperty.getValue()).isEmpty(); + assertThat(updatedProperty.getDefaultValue()).isEqualTo(getInputPropForInput.getDefaultValue()); + assertThat(updatedProperty.getUniqueId()).isEqualTo(getInputPropForInput.getUniqueId()); + } + + private Resource createResourceWithPolicy() { + return createResourceWithPolicies(POLICY_ID); + } + + private Resource createResourceWithPolicies(String ... policies) { + List policiesDef = Stream.of(policies) + .map(this::buildPolicy) + .collect(Collectors.toList()); + + return new ResourceBuilder() + .setUniqueId(RESOURCE_ID) + .setPolicies(policiesDef) + .build(); + } + + private PolicyDefinition buildPolicy(String policyId) { + return PolicyDefinitionBuilder.create() + .setUniqueId(policyId) + .setName(policyId) + .build(); + } + + private PropertyDataDefinition buildGetInputProperty(String inputId) { + return new PropertyDataDefinitionBuilder() + .addGetInputValue(inputId) + .setUniqueId(POLICY_ID + "_" + inputId) + .setDefaultValue("defaultValue") + .setValue(generateGetInputValue(inputId)) + .build(); + } + + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java new file mode 100644 index 0000000000..0c761a948d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java @@ -0,0 +1,69 @@ +package org.openecomp.sdc.be.components.property; + +import org.junit.Before; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; + +public class PropertyDeceleratorTestBase { + + static final String INNER_PROP1 = "ecomp_generated_naming"; + static final String INNER_PROP2 = "naming_policy"; + PropertyDataDefinition prop1, prop2, complexProperty; + + @Before + public void setUp() throws Exception { + prop1 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop1") + .setType("string") + .setName("prop1") + .setValue("value1") + .build(); + + prop2 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop2") + .setType("string") + .setSchemaType("string") + .setName("prop2") + .setValue("[\"a\", \"b\"]") + .build(); + + complexProperty = new PropertyDataDefinitionBuilder() + .setUniqueId("prop3") + .setType("org.openecomp.type1") + .setName("prop3") + .setValue("{\"ecomp_generated_naming\":true\",\"naming_policy\":\"abc\"}") + .build(); + + } + + List createInstancePropInputList(List properties) { + return properties.stream().map(prop -> new ComponentInstancePropInput(new ComponentInstanceProperty(prop))) + .collect(Collectors.toList()); + } + + void verifyInputPropertiesList(List createdInputs, List capturedUpdatedProperties) { + Map propertyIdToCreatedInput = MapUtil.toMap(createdInputs, InputDefinition::getPropertyId); + capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId()))); + } + + String generateGetInputValue(String value) { + return String.format("{\"%s\":\"%s\"}", GET_INPUT, value); + } + + private void verifyInputPropertiesList(PropertyDataDefinition updatedProperty, InputDefinition input) { + assertThat(input.getProperties()).hasSize(1); + assertThat(new ComponentInstanceProperty(updatedProperty)).isEqualTo(input.getProperties().get(0)); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java new file mode 100644 index 0000000000..56aef5d923 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java @@ -0,0 +1,138 @@ +package org.openecomp.sdc.be.components.scheduledtasks; + +import fj.data.Either; +import org.apache.commons.lang.math.NumberUtils; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine; +import org.openecomp.sdc.be.components.scheduledtasks.RecoveryThreadManager.FixEnvironmentTask; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.common.datastructure.Wrapper; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class RecoveryThreadManagerTest extends BeConfDependentTest { + + @InjectMocks + RecoveryThreadManager recoveryThreadManager = new RecoveryThreadManager(); + + private OperationalEnvironmentDao operationalEnvironmentDao = mock(OperationalEnvironmentDao.class); + private EnvironmentsEngine environmentsEngine = mock(EnvironmentsEngine.class); + private ScheduledExecutorService scheduledService = mock(ScheduledExecutorService.class); + + @Before + public void initMocks() { + MockitoAnnotations.initMocks(this); + reset(operationalEnvironmentDao, environmentsEngine, scheduledService); + recoveryThreadManager.init(); + } + + @Test + public void testInit() { + verify(scheduledService, Mockito.times(1)).scheduleAtFixedRate(recoveryThreadManager.task, + NumberUtils.LONG_ZERO, 180L, TimeUnit.SECONDS); + + } + @SuppressWarnings("unchecked") + @Test + public void testTaskNoRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskCassandraCrash() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + Either, CassandraOperationStatus> eitherResult = Either.right(CassandraOperationStatus.GENERAL_ERROR); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(eitherResult); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskMultipleFailedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockEntry = Mockito.mock(OperationalEnvironmentEntry.class); + Either, CassandraOperationStatus> nonEmptyList = Either.left(Arrays.asList(mockEntry, mockEntry, mockEntry)); + Either, CassandraOperationStatus> emptyList = Either.left(Arrays.asList()); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(nonEmptyList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(emptyList); + fixEnvironmentTask.run(); + verify(environmentsEngine, Mockito.times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + @SuppressWarnings("unchecked") + @Test + public void testTaskStaleRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockFailedEntryFirst = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockFailedEntrySecond = Mockito.mock(OperationalEnvironmentEntry.class); + Either, CassandraOperationStatus> failedRecordsList = Either.left(Arrays.asList(mockFailedEntryFirst, mockFailedEntrySecond)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(failedRecordsList); + + OperationalEnvironmentEntry mockInProgressNonStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockInProgressStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 /2)).when(mockInProgressNonStaleEntry).getLastModified(); + doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 * 2)).when(mockInProgressStaleEntry).getLastModified(); + Either, CassandraOperationStatus> inProgressList = Either.left(Arrays.asList(mockInProgressNonStaleEntry, mockInProgressStaleEntry)); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(inProgressList); + fixEnvironmentTask.run(); + + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntryFirst)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntrySecond)); + verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressStaleEntry)); + verify(environmentsEngine, times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressNonStaleEntry)); + + verify(environmentsEngine, times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class)); + + } + + + + @Test + public void testUnconnectedRecords() { + FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task; + OperationalEnvironmentEntry mockCompleteConnected = Mockito.mock(OperationalEnvironmentEntry.class); + OperationalEnvironmentEntry mockCompleteUnconnected = Mockito.mock(OperationalEnvironmentEntry.class); + Either, CassandraOperationStatus> completeRecordsList = Either.left(Arrays.asList(mockCompleteConnected, mockCompleteUnconnected)); + when(environmentsEngine.isInMap(mockCompleteConnected)).thenReturn(true); + when(environmentsEngine.isInMap(mockCompleteUnconnected)).thenReturn(false); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(completeRecordsList); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(Either.left(Arrays.asList())); + when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(Either.left(Arrays.asList())); + fixEnvironmentTask.run(); + + verify(environmentsEngine).createUebTopicsForEnvironment(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).createUebTopicsForEnvironment(mockCompleteConnected); + verify(environmentsEngine).addToMap(mockCompleteUnconnected); + verify(environmentsEngine, times(0)).addToMap(mockCompleteConnected); + verify(environmentsEngine, times(1)).createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class)); + + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java index 55a119e078..32e3f9c10a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java @@ -1,10 +1,10 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; +import java.util.ArrayList; + public class ArtifactBuilder { private ArtifactDefinition artifactDefinition; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java new file mode 100644 index 0000000000..4c137551dc --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java @@ -0,0 +1,51 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +import java.util.ArrayList; + +public class CapabilityDefinitionBuilder { + + private CapabilityDefinition capabilityDefinition; + + public CapabilityDefinitionBuilder() { + capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setProperties(new ArrayList<>()); + } + + public CapabilityDefinitionBuilder addProperty(ComponentInstanceProperty property) { + capabilityDefinition.getProperties().add(property); + return this; + } + + public CapabilityDefinitionBuilder setOwnerId(String ownerId) { + capabilityDefinition.setOwnerId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setOwnerName(String ownerName) { + capabilityDefinition.setOwnerName(ownerName); + return this; + } + + public CapabilityDefinitionBuilder setType(String type) { + capabilityDefinition.setType(type); + return this; + } + + public CapabilityDefinitionBuilder setId(String ownerId) { + capabilityDefinition.setUniqueId(ownerId); + return this; + } + + public CapabilityDefinitionBuilder setName(String name) { + capabilityDefinition.setName(name); + return this; + } + + + public CapabilityDefinition build() { + return capabilityDefinition; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java new file mode 100644 index 0000000000..490140dac0 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java @@ -0,0 +1,155 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public abstract class ComponentBuilder> { + + private T component; + + protected abstract T component(); + + protected abstract ComponentBuilder self(); + + public ComponentBuilder() { + this.component = component(); + } + + public ComponentBuilder(T component) { + this.component = component; + } + + public ComponentBuilder setUniqueId(String id) { + component.setUniqueId(id); + return self(); + } + + public ComponentBuilder setLifeCycleState(LifecycleStateEnum lifeCycleState) { + component.setLifecycleState(lifeCycleState); + return self(); + } + + public ComponentBuilder setLastUpdaterUserId(String lastUpdater) { + component.setLastUpdaterUserId(lastUpdater); + return self(); + } + + public ComponentBuilder setInvariantUUid(String invariantUUid) { + component.setInvariantUUID(invariantUUid); + return self(); + } + + public ComponentBuilder setName(String name) { + component.setName(name); + return self(); + } + + public ComponentBuilder setComponentType(ComponentTypeEnum type) { + component.setComponentType(type); + return self(); + } + + public ComponentBuilder setSystemName(String systemName) { + component.setSystemName(systemName); + return self(); + } + + public ComponentBuilder addComponentInstance(ComponentInstance componentInstance) { + if (component.getComponentInstances() == null) { + component.setComponentInstances(new ArrayList<>()); + } + component.getComponentInstances().add(componentInstance); + return self(); + } + + public ComponentBuilder addInput(InputDefinition input) { + if (component.getInputs() == null) { + component.setInputs(new ArrayList<>()); + } + component.getInputs().add(input); + return self(); + } + + public ComponentBuilder addInput(String inputName) { + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setName(inputName); + inputDefinition.setUniqueId(inputName); + this.addInput(inputDefinition); + return self(); + } + + public ComponentBuilder addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { + if (component.getComponentInstancesProperties() == null) { + component.setComponentInstancesProperties(new HashMap<>()); + } + component.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder addInstanceProperty(String instanceId, String propName) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); + componentInstanceProperty.setName(propName); + this.addInstanceProperty(instanceId, componentInstanceProperty); + return self(); + } + + public ComponentBuilder addInstanceInput(String instanceId, ComponentInstanceInput prop) { + if (component.getComponentInstancesInputs() == null) { + component.setComponentInstancesInputs(new HashMap<>()); + } + component.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); + return self(); + } + + public ComponentBuilder addInstanceInput(String instanceId, String propName) { + ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); + componentInstanceInput.setName(propName); + this.addInstanceInput(instanceId, componentInstanceInput); + return self(); + } + + public ComponentBuilder addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { + if (component.getComponentInstancesRelations() == null) { + component.setComponentInstancesRelations(new ArrayList<>()); + } + component.getComponentInstancesRelations().add(requirementCapabilityRelDef); + return self(); + } + + public ComponentBuilder addPolicy(PolicyDefinition policyDefinition) { + if (component.getPolicies() == null) { + component.setPolicies(new HashMap<>()); + } + component.getPolicies().put(policyDefinition.getUniqueId(), policyDefinition); + return self(); + } + public ComponentBuilder addGroups(GroupDefinition groupDefinition){ + if(component.getGroups() == null){ + component.setGroups(new ArrayList<>()); + } + component.getGroups().add(groupDefinition); + return self(); + } + + public ComponentBuilder setPolicies(List policies) { + component.setPolicies(MapUtil.toMap(policies, PolicyDefinition::getUniqueId)); + return self(); + } + + public T build() { + return component; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java index a99f08c20d..f461806010 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java @@ -1,17 +1,25 @@ package org.openecomp.sdc.be.components.utils; -import java.util.HashMap; -import java.util.Map; - import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.stream.Stream; + public class ComponentInstanceBuilder { private ComponentInstance componentInstance; public ComponentInstanceBuilder() { componentInstance = new ComponentInstance(); + componentInstance.setCapabilities(new HashMap<>()); + componentInstance.setDeploymentArtifacts(new HashMap<>()); + } + + public ComponentInstanceBuilder(ComponentInstance componentInstance) { + this.componentInstance = componentInstance; } public ComponentInstanceBuilder setName(String name) { @@ -19,6 +27,16 @@ public class ComponentInstanceBuilder { return this; } + public ComponentInstanceBuilder setNormalizedName(String name) { + componentInstance.setNormalizedName(name); + return this; + } + + public ComponentInstanceBuilder setUniqueId(String uniqueId) { + componentInstance.setUniqueId(uniqueId); + return this; + } + public ComponentInstanceBuilder setComponentUid(String componentUid) { componentInstance.setComponentUid(componentUid); return this; @@ -35,14 +53,20 @@ public class ComponentInstanceBuilder { } public ComponentInstanceBuilder addDeploymentArtifact(ArtifactDefinition artifactDefinition) { - Map deploymentArtifacts = componentInstance.getDeploymentArtifacts(); - if (deploymentArtifacts == null) { - componentInstance.setDeploymentArtifacts(new HashMap<>()); - } componentInstance.getDeploymentArtifacts().put(artifactDefinition.getArtifactName(), artifactDefinition); return this; } + public ComponentInstanceBuilder addCapability(CapabilityDefinition capabilityDefinition) { + componentInstance.getCapabilities().computeIfAbsent(capabilityDefinition.getType(), key -> new ArrayList<>()).add(capabilityDefinition); + return this; + } + + public ComponentInstanceBuilder addCapabilities(CapabilityDefinition ... capabilities) { + Stream.of(capabilities).forEach(this::addCapability); + return this; + } + public ComponentInstance build() { return componentInstance; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java new file mode 100644 index 0000000000..d8cfa2cb23 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.ComponentInstanceProperty; + +public class ComponentInstancePropertyBuilder extends PropertyDataDefinitionAbstractBuilder { + + @Override + protected PropertyDataDefinitionAbstractBuilder self() { + return this; + } + + @Override + ComponentInstanceProperty propertyDefinition() { + return new ComponentInstanceProperty(); + } + + @Override + public ComponentInstanceProperty build() { + return propertyDefinition; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java new file mode 100644 index 0000000000..d7deaa423a --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupDefinition; + +import java.util.HashMap; +import java.util.Map; + +public class GroupDefinitionBuilder { + private GroupDefinition groupDefinition; + + private GroupDefinitionBuilder() { + this.groupDefinition = new GroupDefinition(); + } + + public static GroupDefinitionBuilder create() { + return new GroupDefinitionBuilder(); + } + + public GroupDefinitionBuilder setUniqueId(String uid) { + groupDefinition.setUniqueId(uid); + return this; + } + + public GroupDefinition build() { + return groupDefinition; + } + + public GroupDefinitionBuilder addMember(String memberName, String memberId) { + Map members = groupDefinition.getMembers(); + if (members == null) { + members = new HashMap<>(); + groupDefinition.setMembers(members); + } + members.put(memberId, memberId); + return this; + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java new file mode 100644 index 0000000000..719967fd6b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java @@ -0,0 +1,43 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.GroupTypeDefinition; + +public class GroupTypeBuilder { + + private GroupTypeDefinition groupTypeDataDefinition; + + public static GroupTypeBuilder create() { + return new GroupTypeBuilder(); + } + + private GroupTypeBuilder() { + this.groupTypeDataDefinition = new GroupTypeDefinition(); + } + + public GroupTypeBuilder setType(String type) { + groupTypeDataDefinition.setType(type); + return this; + } + + public GroupTypeBuilder setUniqueId(String uid) { + groupTypeDataDefinition.setUniqueId(uid); + return this; + } + + public GroupTypeBuilder setVersion(String version) { + groupTypeDataDefinition.setVersion(version); + return this; + } + + public GroupTypeBuilder setDerivedFrom(String derivedFrom) { + groupTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public GroupTypeDefinition build() { + return groupTypeDataDefinition; + } + + + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java index 3a99d54ffa..249cf69112 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java @@ -1,11 +1,5 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -15,6 +9,12 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + public class ObjectGenerator { public static Resource buildResourceWithInputs(String ... inputNames) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java new file mode 100644 index 0000000000..b6aa96e7d7 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; + +import java.util.Set; + +public class OperationalEnvironmentBuilder { + + private OperationalEnvironmentEntry operationalEnvironmentEntry; + + public OperationalEnvironmentBuilder() { + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + } + + public OperationalEnvironmentBuilder setEnvId(String envId) { + operationalEnvironmentEntry.setEnvironmentId(envId); + return this; + } + + public OperationalEnvironmentBuilder setDmaapUebAddress(Set addresses) { + operationalEnvironmentEntry.setDmaapUebAddress(addresses); + return this; + } + + public OperationalEnvironmentBuilder setStatus(EnvironmentStatusEnum status) { + operationalEnvironmentEntry.setStatus(status); + return this; + } + + public OperationalEnvironmentEntry build() { + return operationalEnvironmentEntry; + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java new file mode 100644 index 0000000000..f818c04ccd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PolicyDefinitionBuilder { + + private PolicyDefinition policyDefinition; + + private PolicyDefinitionBuilder() { + this.policyDefinition = new PolicyDefinition(); + } + + public static PolicyDefinitionBuilder create() { + return new PolicyDefinitionBuilder(); + } + + public PolicyDefinitionBuilder setName(String name) { + policyDefinition.setName(name); + return this; + } + + public PolicyDefinitionBuilder setUniqueId(String uid) { + policyDefinition.setUniqueId(uid); + return this; + } + + public PolicyDefinitionBuilder setProperties(PropertyDataDefinition ... props) { + policyDefinition.setProperties(Arrays.asList(props)); + return this; + } + + public PolicyDefinitionBuilder setTargets(Map> targets ){ + policyDefinition.setTargets(targets); + return this; + } + + public PolicyDefinitionBuilder addComponentInstanceTarget(String instId) { + Map> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.COMPONENT_INSTANCES, k -> new ArrayList<>()) + .add(instId); + return this; + } + + public PolicyDefinitionBuilder addGroupTarget(String groupId) { + Map> targets = getTargets(); + targets.computeIfAbsent(PolicyTargetType.GROUPS, k -> new ArrayList<>()).add(groupId); + return this; + } + + public PolicyDefinition build() { + return policyDefinition; + } + + private Map> getTargets() { + Map> targets = policyDefinition.getTargets(); + if (targets == null) { + targets = new HashMap<>(); + policyDefinition.setTargets(targets); + } + return targets; + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java new file mode 100644 index 0000000000..8c2b54f27e --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.components.utils; + + +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +import java.util.List; +import java.util.Map; + +public class PolicyTypeBuilder { + + private PolicyTypeDefinition policyTypeDataDefinition; + + public PolicyTypeBuilder() { + this.policyTypeDataDefinition = new PolicyTypeDefinition(); + } + + public PolicyTypeBuilder setType(String type) { + policyTypeDataDefinition.setType(type); + return this; + } + + public PolicyTypeBuilder setUniqueId(String uid) { + policyTypeDataDefinition.setUniqueId(uid); + return this; + } + + public PolicyTypeBuilder setDerivedFrom(String derivedFrom) { + policyTypeDataDefinition.setDerivedFrom(derivedFrom); + return this; + } + + public PolicyTypeBuilder setVersion(String version) { + policyTypeDataDefinition.setVersion(version); + return this; + } + + public PolicyTypeBuilder setDescription(String version) { + policyTypeDataDefinition.setDescription(version); + return this; + } + + public PolicyTypeBuilder setTargets(List targets) { + policyTypeDataDefinition.setTargets(targets); + return this; + } + + public PolicyTypeBuilder setMetadata(Map metadata) { + policyTypeDataDefinition.setMetadata(metadata); + return this; + } + + public PolicyTypeBuilder setModificationTime(long modificationTime) { + policyTypeDataDefinition.setModificationTime(modificationTime); + return this; + } + + public PolicyTypeBuilder setCreationTime(long creationTime) { + policyTypeDataDefinition.setModificationTime(creationTime); + return this; + } + + public PolicyTypeBuilder setOwner(String owner) { + policyTypeDataDefinition.setOwnerId(owner); + return this; + } + + public PolicyTypeBuilder setHighestVersion(boolean isHighestVersion) { + policyTypeDataDefinition.setHighestVersion(isHighestVersion); + return this; + } + + public PolicyTypeBuilder setProperties(List properties) { + policyTypeDataDefinition.setProperties(properties); + return this; + } + + public PolicyTypeDefinition build() { + return policyTypeDataDefinition; + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java new file mode 100644 index 0000000000..9d5d71d67c --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java @@ -0,0 +1,94 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; + +import java.util.ArrayList; + +public abstract class PropertyDataDefinitionAbstractBuilder> { + + B propertyDefinition; + + protected abstract PropertyDataDefinitionAbstractBuilder self(); + + abstract B propertyDefinition(); + + PropertyDataDefinitionAbstractBuilder() { + propertyDefinition = propertyDefinition(); + } + + public PropertyDataDefinitionAbstractBuilder setUniqueId(String id) { + this.propertyDefinition.setUniqueId(id); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setName(String name) { + this.propertyDefinition.setName(name); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setValue(String value) { + this.propertyDefinition.setValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setDefaultValue(String value) { + this.propertyDefinition.setDefaultValue(value); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setType(String type) { + this.propertyDefinition.setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setOwnerId(String ownerId) { + this.propertyDefinition.setOwnerId(ownerId); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setSchemaType(String type) { + if (propertyDefinition.getSchema() == null) { + propertyDefinition.setSchema(new SchemaDefinition()); + } + if (propertyDefinition.getSchema().getProperty() == null) { + propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); + } + propertyDefinition.getSchema().getProperty().setType(type); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder addGetInputValue(String inputName) { + GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); + getInputValueDataDefinition.setInputName(inputName); + getInputValueDataDefinition.setInputId(inputName); + if (propertyDefinition.getGetInputValues() == null) { + propertyDefinition.setGetInputValues(new ArrayList<>()); + } + propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setIsRequired(boolean required) { + this.propertyDefinition.setRequired(required); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setDescription(String description) { + this.propertyDefinition.setDescription(description); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setIsPassword(boolean isPassword) { + this.propertyDefinition.setRequired(isPassword); + return self(); + } + + public PropertyDataDefinitionAbstractBuilder setStatus(String status) { + this.propertyDefinition.setStatus(status); + return self(); + } + + public abstract B build(); +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java index e7ed170414..85b2228933 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java @@ -1,68 +1,29 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; - -import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; -public class PropertyDataDefinitionBuilder { - - private PropertyDefinition propertyDefinition; - - public PropertyDataDefinitionBuilder() { - propertyDefinition = new PropertyDefinition(); - } - - public PropertyDataDefinitionBuilder setUniqueId(String id) { - this.propertyDefinition.setUniqueId(id); - return this; - } - - public PropertyDataDefinitionBuilder setName(String name) { - this.propertyDefinition.setName(name); - return this; - } +import java.util.List; - public PropertyDataDefinitionBuilder setValue(String value) { - this.propertyDefinition.setValue(value); - return this; - } +public class PropertyDataDefinitionBuilder extends PropertyDataDefinitionAbstractBuilder { - public PropertyDataDefinitionBuilder setDefaultValue(String value) { - this.propertyDefinition.setDefaultValue(value); + protected PropertyDataDefinitionBuilder self() { return this; } - public PropertyDataDefinitionBuilder setType(String type) { - this.propertyDefinition.setType(type); - return this; + @Override + PropertyDefinition propertyDefinition() { + return new PropertyDefinition(); } - public PropertyDataDefinitionBuilder setSchemaType(String type) { - if (propertyDefinition.getSchema() == null) { - propertyDefinition.setSchema(new SchemaDefinition()); - } - if (propertyDefinition.getSchema().getProperty() == null) { - propertyDefinition.getSchema().setProperty(new PropertyDataDefinition()); - } - propertyDefinition.getSchema().getProperty().setType(type); - return this; + @Override + public PropertyDefinition build() { + return propertyDefinition; } - public PropertyDataDefinitionBuilder addGetInputValue(String inputName) { - GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition(); - getInputValueDataDefinition.setInputName(inputName); - getInputValueDataDefinition.setInputId(inputName); - if (propertyDefinition.getGetInputValues() == null) { - propertyDefinition.setGetInputValues(new ArrayList<>()); - } - propertyDefinition.getGetInputValues().add(getInputValueDataDefinition); - return this; + public PropertyDataDefinitionBuilder setConstraints(List constraints) { + propertyDefinition.setConstraints(constraints); + return self(); } - public PropertyDefinition build() { - return propertyDefinition; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java index 8c457f153f..e0d35c6b6a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java @@ -1,12 +1,12 @@ package org.openecomp.sdc.be.components.utils; -import java.util.Collections; - import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; import org.openecomp.sdc.be.model.RelationshipImpl; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import java.util.Collections; + public class RelationsBuilder { private RequirementCapabilityRelDef relation; @@ -16,8 +16,8 @@ public class RelationsBuilder { RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(); RelationshipImpl relationship = new RelationshipImpl(); requirementAndRelationshipPair.setRelationships(relationship); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(requirementAndRelationshipPair); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(requirementAndRelationshipPair); relation.setRelationships(Collections.singletonList(capReqRel)); } @@ -27,17 +27,17 @@ public class RelationsBuilder { } public RelationsBuilder setRequirementName(String reqName) { - relation.getSingleRelationship().getRelation().setRequirement(reqName); + relation.resolveSingleRelationship().getRelation().setRequirement(reqName); return this; } public RelationsBuilder setRelationType(String type) { - relation.getSingleRelationship().getRelation().getRelationship().setType(type); + relation.resolveSingleRelationship().getRelation().getRelationship().setType(type); return this; } public RelationsBuilder setCapabilityUID(String uid) { - relation.getSingleRelationship().getRelation().setCapabilityUid(uid); + relation.resolveSingleRelationship().getRelation().setCapabilityUid(uid); return this; } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java index 3d4a29da71..25468af3c9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java @@ -1,79 +1,26 @@ package org.openecomp.sdc.be.components.utils; -import java.util.ArrayList; -import java.util.HashMap; - -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.Resource; -public class ResourceBuilder { - - private Resource resource; - - public ResourceBuilder() { - this.resource = new Resource(); - } - - public ResourceBuilder(Resource resource) { - this.resource = resource; - } - - public ResourceBuilder setUniqueId(String id) { - resource.setUniqueId(id); - return this; - } - - public ResourceBuilder setInvariantUUid(String invariantUUid) { - resource.setInvariantUUID(invariantUUid); - return this; - } - - public ResourceBuilder setName(String name) { - resource.setName(name); - return this; - } - - public ResourceBuilder setComponentType(ComponentTypeEnum type) { - resource.setComponentType(type); - return this; - } +import java.util.ArrayList; - public ResourceBuilder setSystemName(String systemName) { - resource.setSystemName(systemName); - return this; - } +public class ResourceBuilder extends ComponentBuilder { - public ResourceBuilder addComponentInstance(ComponentInstance componentInstance) { - if (resource.getComponentInstances() == null) { - resource.setComponentInstances(new ArrayList<>()); - } - resource.getComponentInstances().add(componentInstance); - return this; - } + private Resource resource; - public ResourceBuilder addInput(InputDefinition input) { - if (resource.getInputs() == null) { - resource.setInputs(new ArrayList<>()); - } - resource.getInputs().add(input); - return this; + @Override + protected Resource component() { + resource = new Resource(); + return resource; } - public ResourceBuilder addInput(String inputName) { - InputDefinition inputDefinition = new InputDefinition(); - inputDefinition.setName(inputName); - inputDefinition.setUniqueId(inputName); - this.addInput(inputDefinition); + @Override + protected ComponentBuilder self() { return this; } - public ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { + ResourceBuilder addProperty(PropertyDefinition propertyDefinition) { if (resource.getProperties() == null) { resource.setProperties(new ArrayList<>()); } @@ -81,46 +28,14 @@ public class ResourceBuilder { return this; } - public ResourceBuilder addInstanceProperty(String instanceId, ComponentInstanceProperty prop) { - if (resource.getComponentInstancesProperties() == null) { - resource.setComponentInstancesProperties(new HashMap<>()); - } - resource.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - - public ResourceBuilder addInstanceProperty(String instanceId, String propName) { - ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); - componentInstanceProperty.setName(propName); - this.addInstanceProperty(instanceId, componentInstanceProperty); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, ComponentInstanceInput prop) { - if (resource.getComponentInstancesInputs() == null) { - resource.setComponentInstancesInputs(new HashMap<>()); - } - resource.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop); - return this; - } - public ResourceBuilder addInstanceInput(String instanceId, String propName) { - ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput(); - componentInstanceInput.setName(propName); - this.addInstanceInput(instanceId, componentInstanceInput); - return this; + public ResourceBuilder() { + super(); } - public ResourceBuilder addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) { - if (resource.getComponentInstancesRelations() == null) { - resource.setComponentInstancesRelations(new ArrayList<>()); - } - resource.getComponentInstancesRelations().add(requirementCapabilityRelDef); - return this; + public ResourceBuilder(Resource resource) { + super(resource); } - - public Resource build() { - return resource; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java new file mode 100644 index 0000000000..d85ad9bcc2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.components.utils; + +import org.openecomp.sdc.be.model.Service; + +public class ServiceBuilder extends ComponentBuilder { + + private Service service; + + public ServiceBuilder(Service component) { + super(component); + } + + public ServiceBuilder() { + super(); + } + + @Override + protected Service component() { + service = new Service(); + return service; + } + + @Override + protected ComponentBuilder self() { + return this; + } + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java new file mode 100644 index 0000000000..be19e8b795 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.be.components.utils; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UtilsTest { + + @Test + public void testThatEmptyListReturns0() { + List existingResourceNames = new ArrayList<>(); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isZero(); + } + + @Test + public void testListWithValidValue() { + List existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithInvalidSingleValue() { + List existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(1); + } + + @Test + public void testListWithValidValues() { + List existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..2"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } + + @Test + public void testListWithInvalidValue() { + List existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15", + "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection"); + int counter = Utils.getNextCounter(existingResourceNames); + assertThat(counter).isEqualTo(16); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java new file mode 100644 index 0000000000..df48a538a5 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java @@ -0,0 +1,153 @@ +package org.openecomp.sdc.be.components.validation; + +import fj.data.Either; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine; +import org.openecomp.sdc.be.components.impl.ActivationRequestInformation; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry; +import org.openecomp.sdc.exception.ResponseFormat; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class ServiceDistributionValidationTest { + + private static final String USER_ID = "userId"; + private static final String SERVICE_ID = "serviceId"; + private static final String ENV_ID = "envId"; + + @InjectMocks + private ServiceDistributionValidation testInstance; + + @Mock + private UserValidations userValidations; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private OperationalEnvironmentDao operationalEnvironmentDao; + + @Mock + private IDistributionEngine distributionEngine; + + @Mock + private ComponentsUtils componentsUtils; + + private User user; + private Service service; + private OperationalEnvironmentEntry operationalEnvironmentEntry; + private ResponseFormat errResponse; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + user = new User(); + user.setUserId(USER_ID); + errResponse = new ResponseFormat(); + service = new Service(); + service.setUniqueId(SERVICE_ID); + service.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + operationalEnvironmentEntry = new OperationalEnvironmentEntry(); + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.COMPLETED); + } + + @Test + public void validateActivateServiceRequest_userNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.right(errResponse)); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(toscaOperationFacade, operationalEnvironmentDao, componentsUtils); + } + + @Test + public void validateActivateServiceRequest_ServiceNotExist() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR, ComponentTypeEnum.SERVICE)).thenReturn(ActionStatus.GENERAL_ERROR); + when(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue())).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_ServiceLifeCycleStateNotReadyForDistribution() { + service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE))).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + verifyZeroInteractions(operationalEnvironmentDao); + } + + @Test + public void validateActivateServiceRequest_operationalEnvNotExist() throws Exception { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(null); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_operationalEnvStatusNotComplete() { + operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_couldNotParseDistributionData() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo()); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_distributionDataHasNoWorkloadContext() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("")); + assertEquals(errResponse, activateServiceReq.right().value()); + } + + @Test + public void validateActivateServiceRequest_requestValid() { + when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user)); + when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service)); + when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry); + Either activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("context")); + assertEquals(service, activateServiceReq.left().value().getServiceToActivate()); + assertEquals("context", activateServiceReq.left().value().getWorkloadContext()); + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java new file mode 100644 index 0000000000..0408d31606 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java @@ -0,0 +1,7 @@ +package org.openecomp.sdc.be.config; + +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringConfig { +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java new file mode 100644 index 0000000000..4f90a0a42f --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.be.datamodel; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.openecomp.sdc.be.components.utils.ServiceBuilder; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; + +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UiComponentDataConverterTest { + + private PolicyDefinition policy1, policy2; + + @Before + public void setUp() throws Exception { + policy1 = PolicyDefinitionBuilder.create() + .setName("policy1") + .setUniqueId("uid1") + .build(); + + policy2 = PolicyDefinitionBuilder.create() + .setName("policy2") + .setUniqueId("uid2") + .build(); + } + + @Test + public void getUiDataTransferFromResourceByParams_policies_noPoliciesForResource() { + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(new Resource(), Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEmpty(); + } + + @Test + public void getUiDataTransferFromServiceByParams_policies_noPoliciesForResource() { + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(new Service(), Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEmpty(); + } + + @Test + public void getUiDataTransferFromResourceByParams_policies() { + Resource resourceWithPolicies = buildResourceWithPolicies(); + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resourceWithPolicies, Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList()); + } + + @Test + public void getUiDataTransferFromServiceByParams_policies() { + Service resourceWithPolicies = buildServiceWithPolicies(); + UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(resourceWithPolicies, Collections.singletonList("policies")); + assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList()); + } + + private Resource buildResourceWithPolicies() { + return new ResourceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } + + private Service buildServiceWithPolicies() { + return new ServiceBuilder() + .addPolicy(policy1) + .addPolicy(policy2) + .build(); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java index 290a5f4d1d..a80999a25b 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java @@ -20,18 +20,13 @@ package org.openecomp.sdc.be.distribution; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse; import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask; @@ -43,148 +38,384 @@ import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse; import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse; import org.openecomp.sdc.common.datastructure.Wrapper; -public class DistributionBusinessLogicTest extends BaseConfDependentTest { - - @InjectMocks - DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class); - - CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); - AuditHandler auditHandler = Mockito.mock(AuditHandler.class); - - @Test - public void testHandleRegistrationHappyScenario() { - CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); - - Wrapper responseWrapper = new Wrapper<>(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); - distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); - - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - Mockito.verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); - - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_OK); - - TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity(); - - String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName(); - assertEquals(expectedStatusTopicName, actualStatusTopicName); - - String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName(); - assertEquals(expectedNotificationTopicName, actualNotificationTopicName); - - } - - @Test - public void testHandleRegistrationFailedScenario() { - CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, HttpStatus.SC_SERVICE_UNAVAILABLE); - DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); - String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - - Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); - Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) - .thenReturn(errorResponse); - - Wrapper responseWrapper = new Wrapper<>(); +import javax.ws.rs.core.Response; - distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName; + +public class DistributionBusinessLogicTest extends BeConfDependentTest { + + @InjectMocks + DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class); + + CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class); + AuditHandler auditHandler = Mockito.mock(AuditHandler.class); + + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, + HttpStatus.SC_SERVICE_UNAVAILABLE); + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + Mockito.reset(cambriaHandler); + } + + @Test + public void testHandleRegistrationNoConsumeStatusTopic() { + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + Wrapper responseWrapper = new Wrapper<>(); + + testHandleRegistrationBasic(registrationRequest, responseWrapper); + + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + @Test + public void testHandleRegistrationConsumeStatusTopic() { + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper responseWrapper = new Wrapper<>(); + + testHandleRegistrationBasic(registrationRequest, responseWrapper); + + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + } + /** + * Registration Fails When registering as consumer to Notification With Consumer Status flag false. + */ + @Test + public void testHandleRegistrationFailedScenario() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + Wrapper responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + /** + * Registration Fails When registering as consumer to Notification With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + } + + /** + * Registration Fails When registering as consumer to status With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic2() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + //Failing on new registration + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Unregistered Activated (rollback) + verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + + } + + + /** + * Registration Fails When registering as PRODUCER to status With Consumer Status flag true. + */ + @Test + public void testHandleRegistrationFailedConsumeStatusTopic3() { + + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true); + Wrapper responseWrapper = new Wrapper<>(); + String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + + //Failing on new registration + Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(errorResponse); + testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen); + //Registered + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName); + //Did Not Register + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName); + //Unregistered Not Activated + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(), + config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), + SubscriberTypeEnum.CONSUMER, expectedStatusTopicName); + + } + + @SuppressWarnings("unchecked") + @Test + public void testHandleUnRegistrationHappyScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + + Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString())) + .thenReturn(okResponse); + + Wrapper responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString()); + + Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), + Mockito.anyString()); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + + String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); + + String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + + } + + @Test + public void testHandleUnRegistrationFailedScenario() { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, + HttpStatus.SC_INTERNAL_SERVER_ERROR); + + Wrapper responseWrapper = new Wrapper<>(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false); + DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); + String expectedStatusTopicName = DistributionEngineInitTask + .buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = DistributionEngineInitTask + .buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(okResponse); + Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedNotificationTopicName)).thenReturn(errorResponse); + + distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic( + Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), + Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString()); + Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic( + Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString()); + + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + + TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - Mockito.verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER); + String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); - } + assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), + CambriaOperationStatus.AUTHENTICATION_ERROR); + assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); - @Test - public void testHandleUnRegistrationHappyScenario() { - CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + } - Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse); + @SuppressWarnings("unchecked") + private void testHandleRegistrationBasic(RegistrationRequest registrationRequest, + Wrapper responseWrapper) { + CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); + Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString())) + .thenReturn(okResponse); - Wrapper responseWrapper = new Wrapper<>(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); - distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); + String expectedStatusTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), + registrationRequest.getDistrEnvName()); + String expectedNotificationTopicName = buildTopicName( + configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), + registrationRequest.getDistrEnvName()); - Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); - Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class)); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.PRODUCER, expectedStatusTopicName); + verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, + registrationRequest, SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName); - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_OK); + verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString()); - TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_OK); - String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); - assertEquals(expectedStatusTopicName, actualStatusTopicName); + TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity(); - String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); - assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName(); + assertEquals(expectedStatusTopicName, actualStatusTopicName); - assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK); - assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName(); + assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + } - } + private void testHandleRegistrationFailed(RegistrationRequest registrationRequest, + Wrapper responseWrapper, Runnable failWhen) { + String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - @Test - public void testHandleUnRegistrationFailedScenario() { - CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK); - CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR); - Wrapper responseWrapper = new Wrapper<>(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv"); - DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration(); - String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName()); - String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName()); - Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse); - Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER)) - .thenReturn(errorResponse); - distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler); - Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER); - Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER); - assertTrue(!responseWrapper.isEmpty()); - Response response = responseWrapper.getInnerElement(); - assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); + when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER, + expectedStatusTopicName)).thenReturn(okResponse); - TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity(); + when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(), + config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER, + expectedStatusTopicName)).thenReturn(okResponse); - String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName(); - assertEquals(expectedStatusTopicName, actualStatusTopicName); + failWhen.run(); - String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName(); - assertEquals(expectedNotificationTopicName, actualNotificationTopicName); + distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler); - assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.AUTHENTICATION_ERROR); - assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK); + assertTrue(!responseWrapper.isEmpty()); + Response response = responseWrapper.getInnerElement(); + assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - @Before - public void init() { - MockitoAnnotations.initMocks(this); - Mockito.reset(cambriaHandler); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java index 4e27c30f8a..4257a88a02 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java @@ -20,17 +20,9 @@ package org.openecomp.sdc.be.distribution; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.junit.Test; import org.mockito.InjectMocks; -import org.openecomp.sdc.be.components.BaseConfDependentTest; +import org.openecomp.sdc.be.components.BeConfDependentTest; import org.openecomp.sdc.be.components.distribution.engine.ArtifactInfoImpl; import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -38,69 +30,77 @@ import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; -public class ServiceDistributionArtifactsBuilderTest extends BaseConfDependentTest { +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertTrue; + +public class ServiceDistributionArtifactsBuilderTest extends BeConfDependentTest { + + @InjectMocks + ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder(); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testConvertServiceArtifactsToArtifactInfo() { + + Service service = new Service(); + String serviceName = "myService"; + String serviceVersion = "1.0"; + String serviceId = "serviceId"; + service.setName(serviceName); + service.setVersion(serviceVersion); + service.setUniqueId(serviceId); + + + String artifactName = "service-Myservice-template.yml"; + String artifactLabel = "assettoscatemplate"; + String esArtifactId = "123123dfgdfgd0"; + byte[] payload = "some payload".getBytes(); + + ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); + toscaTemplateArtifact.setArtifactName(artifactName); + toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); + toscaTemplateArtifact.setArtifactLabel(artifactLabel); + toscaTemplateArtifact.setEsId(esArtifactId); + toscaTemplateArtifact.setUniqueId(esArtifactId); + toscaTemplateArtifact.setPayload(payload); + + Map toscaArtifacts = new HashMap<>(); + toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); + service.setToscaArtifacts(toscaArtifacts); - @InjectMocks - ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder(); - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void testConvertServiceArtifactsToArtifactInfo() { + ArtifactDefinition deploymentArtifact = new ArtifactDefinition(); + deploymentArtifact.setArtifactName("deployment.yaml"); + deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType()); + deploymentArtifact.setArtifactLabel("deployment"); + deploymentArtifact.setEsId("deployment007"); + deploymentArtifact.setUniqueId("deployment007"); + deploymentArtifact.setPayload(payload); + Map deploymentArtifacts = new HashMap<>(); + deploymentArtifacts.put("deployment", deploymentArtifact); + service.setDeploymentArtifacts(deploymentArtifacts); - Service service = new Service(); - String serviceName = "myService"; - String serviceVersion = "1.0"; - String serviceId = "serviceId"; - service.setName(serviceName); - service.setVersion(serviceVersion); - service.setUniqueId(serviceId); - - - String artifactName = "service-Myservice-template.yml"; - String artifactLabel = "assettoscatemplate"; - String esArtifactId = "123123dfgdfgd0"; - byte[] payload = "some payload".getBytes(); - - ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition(); - toscaTemplateArtifact.setArtifactName(artifactName); - toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()); - toscaTemplateArtifact.setArtifactLabel(artifactLabel); - toscaTemplateArtifact.setEsId(esArtifactId); - toscaTemplateArtifact.setUniqueId(esArtifactId); - toscaTemplateArtifact.setPayload(payload); - - Map toscaArtifacts = new HashMap<>(); - toscaArtifacts.put(artifactLabel, toscaTemplateArtifact); - service.setToscaArtifacts(toscaArtifacts); - - ArtifactDefinition deploymentArtifact = new ArtifactDefinition(); - deploymentArtifact.setArtifactName("deployment.yaml"); - deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType()); - deploymentArtifact.setArtifactLabel("deployment"); - deploymentArtifact.setEsId("deployment007"); - deploymentArtifact.setUniqueId("deployment007"); - deploymentArtifact.setPayload(payload); - Map deploymentArtifacts = new HashMap<>(); - deploymentArtifacts.put("deployment", deploymentArtifact); - service.setDeploymentArtifacts(deploymentArtifacts); - - Class targetClass = ServiceDistributionArtifactsBuilder.class; - String methodName = "convertServiceArtifactsToArtifactInfo"; - Object[] argObjects = {service}; - Class[] argClasses = {Service.class}; - try { - Method method = targetClass.getDeclaredMethod(methodName, argClasses); - method.setAccessible(true); - List convertServiceArtifactsToArtifactInfoRes = - (List) method.invoke(serviceDistributionArtifactsBuilder, argObjects); - assertTrue(convertServiceArtifactsToArtifactInfoRes != null); - assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2); - List artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList()); - assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml")); - } - catch (Exception e) { - e.printStackTrace(); - } - } + Class targetClass = ServiceDistributionArtifactsBuilder.class; + String methodName = "convertServiceArtifactsToArtifactInfo"; + Object[] argObjects = {service}; + Class[] argClasses = {Service.class}; + try { + Method method = targetClass.getDeclaredMethod(methodName, argClasses); + method.setAccessible(true); + List convertServiceArtifactsToArtifactInfoRes = + (List) method.invoke(serviceDistributionArtifactsBuilder, argObjects); + assertTrue(convertServiceArtifactsToArtifactInfoRes != null); + assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2); + List artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList()); + assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml")); + } + catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java index 74f0eac5ad..29b43c1920 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java @@ -20,6 +20,11 @@ package org.openecomp.sdc.be.distribution; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; +import org.openecomp.sdc.be.components.distribution.engine.INotificationData; +import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; + import java.util.ArrayList; import java.util.List; import java.util.Timer; @@ -35,154 +40,148 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler; -import org.openecomp.sdc.be.components.distribution.engine.INotificationData; -import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; - public class TestQueue { - public static void main(String[] args) { - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setNameFormat("distribution-notification-thread"); - ThreadFactory threadFactory = threadFactoryBuilder.build(); - // TODO: add the package of google to the pom - - ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue(), threadFactory); - // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, - // TimeUnit.SECONDS, new ArrayBlockingQueue(20)); - - // 2 threads are always up and they handle the tasks. in case core size - // is 0, only one is handles the tasks. - // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, - // TimeUnit.SECONDS, new ArrayBlockingQueue(20)); - - // TODO : check what happen when the number of threads are full. Throw - // RejectedExecutionException - // TODO : check what happen whether the pool is full and the size of - // pool - - ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory); - Runnable task = new Runnable() { - - @Override - public void run() { - try { - System.out.println("iN SLEEP" + Thread.currentThread()); - Thread.sleep(10 * 1000); - System.out.println("OUT SLEEP"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }; - - for (int i = 0; i < 4; i++) { - try { - executorService.submit(task); - } catch (RejectedExecutionException e) { - e.printStackTrace(); - } - } - - newCachedThreadPool.submit(task); - System.out.println("After submitting the task"); - - MyWorker[] watchThreads = new MyWorker[1]; - BlockingQueue queue = new ArrayBlockingQueue<>(5); - for (int i = 0; i < watchThreads.length; i++) { - MyWorker myWorker = new MyWorker(queue); - myWorker.start(); - } - - for (int i = 0; i < 1; i++) { - try { - queue.put("message " + i); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - - public static class MyTimerTask extends TimerTask { - - AtomicBoolean state; - Thread thread; - - public MyTimerTask(AtomicBoolean state, Thread thread) { - super(); - this.state = state; - this.thread = thread; - - System.out.println("After create timer"); - } - - @Override - public void run() { - System.out.println("In running of Timer task"); - if (state.get() == false) { - System.out.println("In running of Timer task. Going to interrupt thread"); - // thread.interrupt(); - } else { - System.out.println("In running of Timer task. Finished."); - } - } - - } - - public static class MyWorker extends Thread { - - boolean active = true; - private final BlockingQueue queue; - - public MyWorker(BlockingQueue queue) { - this.queue = queue; - } - - Timer timer = new Timer(); - - public void run() { - try { - while (active) { - String s = queue.take(); - System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s); - - AtomicBoolean atomicBoolean = new AtomicBoolean(false); - MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this); - timer.schedule(myTimerTask, 10 * 1000); - doWork(s); - atomicBoolean.set(true); - - } - } catch (InterruptedException ie) { - - System.out.println("Interrupted our thread"); - ie.printStackTrace(); - } - } - - private void doWork(String s) { - // TODO Auto-generated method stub - - CambriaHandler cambriaHandler = new CambriaHandler(); - INotificationData data = new NotificationDataImpl(); - List servers = new ArrayList<>(); - servers.add("aaaaaaa"); - cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data); - - System.out.println("IN WORK " + s); - try { - Thread.sleep(1 * 1000); - } catch (InterruptedException e) { - - for (int i = 0; i < 10; i++) { - System.out.println("*************************************************"); - } - e.printStackTrace(); - } - } - } + public static void main(String[] args) { + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + threadFactoryBuilder.setNameFormat("distribution-notification-thread"); + ThreadFactory threadFactory = threadFactoryBuilder.build(); + // TODO: add the package of google to the pom + + ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue(), threadFactory); + // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, + // TimeUnit.SECONDS, new ArrayBlockingQueue(20)); + + // 2 threads are always up and they handle the tasks. in case core size + // is 0, only one is handles the tasks. + // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L, + // TimeUnit.SECONDS, new ArrayBlockingQueue(20)); + + // TODO : check what happen when the number of threads are full. Throw + // RejectedExecutionException + // TODO : check what happen whether the pool is full and the size of + // pool + + ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory); + Runnable task = new Runnable() { + + @Override + public void run() { + try { + System.out.println("iN SLEEP" + Thread.currentThread()); + Thread.sleep(10 * 1000); + System.out.println("OUT SLEEP"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + + for (int i = 0; i < 4; i++) { + try { + executorService.submit(task); + } catch (RejectedExecutionException e) { + e.printStackTrace(); + } + } + + newCachedThreadPool.submit(task); + System.out.println("After submitting the task"); + + MyWorker[] watchThreads = new MyWorker[1]; + BlockingQueue queue = new ArrayBlockingQueue<>(5); + for (int i = 0; i < watchThreads.length; i++) { + MyWorker myWorker = new MyWorker(queue); + myWorker.start(); + } + + for (int i = 0; i < 1; i++) { + try { + queue.put("message " + i); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + } + + public static class MyTimerTask extends TimerTask { + + AtomicBoolean state; + Thread thread; + + public MyTimerTask(AtomicBoolean state, Thread thread) { + super(); + this.state = state; + this.thread = thread; + + System.out.println("After create timer"); + } + + @Override + public void run() { + System.out.println("In running of Timer task"); + if (state.get() == false) { + System.out.println("In running of Timer task. Going to interrupt thread"); + // thread.interrupt(); + } else { + System.out.println("In running of Timer task. Finished."); + } + } + + } + + public static class MyWorker extends Thread { + + boolean active = true; + private final BlockingQueue queue; + + public MyWorker(BlockingQueue queue) { + this.queue = queue; + } + + Timer timer = new Timer(); + + public void run() { + try { + while (active) { + String s = queue.take(); + System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s); + + AtomicBoolean atomicBoolean = new AtomicBoolean(false); + MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this); + timer.schedule(myTimerTask, 10 * 1000); + doWork(s); + atomicBoolean.set(true); + + } + } catch (InterruptedException ie) { + + System.out.println("Interrupted our thread"); + ie.printStackTrace(); + } + } + + private void doWork(String s) { + // TODO Auto-generated method stub + + CambriaHandler cambriaHandler = new CambriaHandler(); + INotificationData data = new NotificationDataImpl(); + List servers = new ArrayList<>(); + servers.add("aaaaaaa"); + cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data); + + System.out.println("IN WORK " + s); + try { + Thread.sleep(1 * 1000); + } catch (InterruptedException e) { + + for (int i = 0; i < 10; i++) { + System.out.println("*************************************************"); + } + e.printStackTrace(); + } + } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java index 3aa143a389..253fd31390 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java @@ -20,17 +20,8 @@ package org.openecomp.sdc.be.distribution.servlet; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.apache.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; @@ -42,6 +33,7 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.distribution.AuditHandler; import org.openecomp.sdc.be.distribution.DistributionBusinessLogic; import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest; @@ -52,107 +44,116 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class DistributionServletTest extends JerseyTest { - public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - public static final HttpSession session = Mockito.mock(HttpSession.class); - public static final ServletContext servletContext = Mockito.mock(ServletContext.class); - public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); - public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class); - public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); - - public static final String ENV_NAME = "myEnv"; - public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification"; - public static final String STATUS_TOPIC = ENV_NAME + "_Status"; - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - when(request.getSession()).thenReturn(session); - when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID"); - - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic); - when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine); - when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK); - when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK); - - mockBusinessLogicResponse(); - - } - - private static void mockBusinessLogicResponse() { - // Mock Register - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Wrapper responseWrapper = (Wrapper) args[0]; - TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); - okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); - okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); - - return true; - } - }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); - - // Mock Unregister - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Wrapper responseWrapper = (Wrapper) args[0]; - TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); - okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); - okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); - responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); - - return true; - } - }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); - } - - @Test - public void registerSuccessTest() { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); - Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); - assertTrue(response.getStatus() == HttpStatus.SC_OK); - - } - - @Test - public void unRegisterSuccessTest() { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME); - Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); - assertTrue(response.getStatus() == HttpStatus.SC_OK); - - } - - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(DistributionServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class); + public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class); + + public static final String ENV_NAME = "myEnv"; + public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification"; + public static final String STATUS_TOPIC = ENV_NAME + "_Status"; + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic); + when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine); + when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK); + when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK); + + mockBusinessLogicResponse(); + + } + + private static void mockBusinessLogicResponse() { + // Mock Register + Mockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper responseWrapper = (Wrapper) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + + // Mock Unregister + Mockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + Wrapper responseWrapper = (Wrapper) args[0]; + TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse(); + okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC); + okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC); + responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build()); + + return true; + } + }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class)); + } + + @Test + public void registerSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME, false); + Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Test + public void unRegisterSuccessTest() { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME, false); + Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_OK); + + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(DistributionServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java index 1df88c3686..8a40e83506 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java @@ -20,56 +20,56 @@ package org.openecomp.sdc.be.ecomp; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.openecomp.sdc.common.config.EcompClassification; +import org.openecomp.sdc.common.config.EcompErrorCode; +import org.openecomp.sdc.common.config.EcompErrorEnum; +import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.openecomp.sdc.common.config.EcompClassification; -import org.openecomp.sdc.common.config.EcompErrorCode; -import org.openecomp.sdc.common.config.EcompErrorEnum; -import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv; +import static org.junit.Assert.assertTrue; public class GenerateEcompErrorFileTest { - @Test - public void verifyNoDuplicatesInEcompErrorCodes() { + @Test + public void verifyNoDuplicatesInEcompErrorCodes() { - EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); + EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values(); - Map> map = new HashMap>(); - for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) { + Map> map = new HashMap>(); + for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) { - List list = map.get(ecompErrorEnum.getEcompErrorCode()); - if (list == null) { - list = new ArrayList<>(); + List list = map.get(ecompErrorEnum.getEcompErrorCode()); + if (list == null) { + list = new ArrayList<>(); - list.add(ecompErrorEnum.getClassification()); + list.add(ecompErrorEnum.getClassification()); - map.put(ecompErrorEnum.getEcompErrorCode(), list); - } else { - if (list.contains(ecompErrorEnum.getClassification())) { - assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false); - } else { - list.add(ecompErrorEnum.getClassification()); - } + map.put(ecompErrorEnum.getEcompErrorCode(), list); + } else { + if (list.contains(ecompErrorEnum.getClassification())) { + assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false); + } else { + list.add(ecompErrorEnum.getClassification()); + } - } + } - } + } - } + } - @Test - public void generateEcompErrorFileInTarget() { + @Test + public void generateEcompErrorFileInTarget() { - GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); - boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false); - assertTrue("check result from file generation", result); + GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv(); + boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false); + assertTrue("check result from file generation", result); - } + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java index 810da4c10b..fa43523c79 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java @@ -21,19 +21,7 @@ package org.openecomp.sdc.be.externalapi.servlet; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import fj.data.Either; import org.apache.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; @@ -48,6 +36,7 @@ import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; @@ -62,77 +51,88 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.FunctionalInterfaces; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class AssetsDataServletTest extends JerseyTest { - public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - public static final HttpSession session = Mockito.mock(HttpSession.class); - public static final ServletContext servletContext = Mockito.mock(ServletContext.class); - public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); - public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); - public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); - public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); - public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class); - public static final Resource resource = Mockito.mock(Resource.class); - public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class); - public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class); - public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class); -// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class); - public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();; - - - - - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - when(request.getSession()).thenReturn(session); - when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId"); - when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID"); - when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources")); - - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - - when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); - when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic); - - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - mockResponseFormat(); - - when(resource.getName()).thenReturn("MockVFCMT"); - when(resource.getSystemName()).thenReturn("mockvfcmt"); - Either eitherRet = Either.left(resource); - when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet); - - when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); - when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic); - when(categoryDefinition.getName()).thenReturn("Template"); - when(subCategoryDefinition.getName()).thenReturn("Monitoring Template"); - when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition)); - when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition))); - when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource)); - when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter); - - Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(), - Mockito.eq(true)); - - - - } - - - - private static void mockResponseFormat() { - when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer) invocation -> { + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); + public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class); + public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class); + public static final Resource resource = Mockito.mock(Resource.class); + public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class); + public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class); + public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class); +// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class); + public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();; + + + + + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId"); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID"); + when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources")); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic); + + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + mockResponseFormat(); + + when(resource.getName()).thenReturn("MockVFCMT"); + when(resource.getSystemName()).thenReturn("mockvfcmt"); + Either eitherRet = Either.left(resource); + when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet); + + when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); + when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic); + when(categoryDefinition.getName()).thenReturn("Template"); + when(subCategoryDefinition.getName()).thenReturn("Monitoring Template"); + when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition)); + when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition))); + when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource)); + when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter); + + Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(), + Mockito.eq(true)); + + + + } + + + private static void mockResponseFormat() { + when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer) invocation -> { ResponseFormat ret; final ActionStatus actionStatus = invocation.getArgument(0); switch( actionStatus ){ @@ -147,52 +147,52 @@ public class AssetsDataServletTest extends JerseyTest { } return ret; }); - } - - - - @Test - public void createVfcmtHappyScenario() { - final JSONObject createRequest = buildCreateJsonRequest(); - Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID") - .post(Entity.json(createRequest.toJSONString()), Response.class); - assertTrue(response.getStatus() == HttpStatus.SC_CREATED); - - } - private static final String BASIC_CREATE_REQUEST = "{\r\n" + - " \"name\": \"VFCMT_1\",\r\n" + - " \"description\": \"VFCMT Description\",\r\n" + - " \"resourceType\" : \"VFCMT\",\r\n" + - " \"category\": \"Template\",\r\n" + - " \"subcategory\": \"Monitoring Template\",\r\n" + - " \"vendorName\" : \"DCAE\",\r\n" + - " \"vendorRelease\" : \"1.0\",\r\n" + - " \"tags\": [\r\n" + - " \"VFCMT_1\"\r\n" + - " ],\r\n" + - " \"icon\" : \"defaulticon\",\r\n" + - " \"contactId\": \"cs0008\"\r\n" + - "}"; - private JSONObject buildCreateJsonRequest() { - - JSONParser parser = new JSONParser(); - JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST)); - return jsonObj; - - } - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(CrudExternalServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } + } + + + + @Test + public void createVfcmtHappyScenario() { + final JSONObject createRequest = buildCreateJsonRequest(); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID") + .post(Entity.json(createRequest.toJSONString()), Response.class); + assertTrue(response.getStatus() == HttpStatus.SC_CREATED); + + } + private static final String BASIC_CREATE_REQUEST = "{\r\n" + + " \"name\": \"VFCMT_1\",\r\n" + + " \"description\": \"VFCMT Description\",\r\n" + + " \"resourceType\" : \"VFCMT\",\r\n" + + " \"category\": \"Template\",\r\n" + + " \"subcategory\": \"Monitoring Template\",\r\n" + + " \"vendorName\" : \"DCAE\",\r\n" + + " \"vendorRelease\" : \"1.0\",\r\n" + + " \"tags\": [\r\n" + + " \"VFCMT_1\"\r\n" + + " ],\r\n" + + " \"icon\" : \"defaulticon\",\r\n" + + " \"contactId\": \"cs0008\"\r\n" + + "}"; + private JSONObject buildCreateJsonRequest() { + + JSONParser parser = new JSONParser(); + JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST)); + return jsonObj; + + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(CrudExternalServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java new file mode 100644 index 0000000000..f185bffc17 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java @@ -0,0 +1,603 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * 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.openecomp.sdc.be.externalapi.servlet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic; +import org.openecomp.sdc.be.components.path.utils.GraphTestUtils; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.DAOTitanStrategy; +import org.openecomp.sdc.be.dao.TitanClientStrategy; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dto.ExternalRefDTO; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; +import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.ConfigurationSource; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.impl.ExternalConfiguration; +import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpStatus; +import org.springframework.web.context.WebApplicationContext; + +import fj.data.Either; + +public class ExternalRefServletTest extends JerseyTest { + + private static ConfigurationManager configurationManager; + static String serviceVertexUuid; + private static final HttpSession session = Mockito.mock(HttpSession.class); + private static final ServletContext servletContext = Mockito.mock(ServletContext.class); + + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class); + private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class); + private static final ToscaOperationFacade toscaOperationFacadeMock = Mockito.mock(ToscaOperationFacade.class); + private static final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); + private static final TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static final ICacheMangerOperation cacheManagerOperation = Mockito.mock(ICacheMangerOperation.class); + + private static final String COMPONENT_ID = "ci-MyComponentName"; + + private static final String FAKE_COMPONENT_ID = "ci-MyFAKEComponentName"; + private static final String MONITORING_OBJECT_TYPE = "monitoring"; + private static final String WORKFLOW_OBJECT_TYPE = "workflow"; + private static final String VERSION = "0.1"; + private static final String FAKE_VERSION = "0.5"; + private static final String REF_1 = "ref1"; + private static final String REF_2 = "ref2"; + private static final String REF_3 = "ref3"; + private static final String REF_4 = "ref4"; + private static final String REF_5 = "ref5"; + //workflow + private static final String REF_6 = "ref6"; + + @Configuration + static class TestSpringConfig { + + private GraphVertex serviceVertex; + private ExternalReferencesOperation externalReferenceOperation; + private TitanDao titanDao; + + @Bean + ExternalRefsServlet externalRefsServlet(){ + return new ExternalRefsServlet(externalRefsBusinessLogic(), componentUtils); + } + + @Bean + ExternalRefsBusinessLogic externalRefsBusinessLogic() { + return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(), graphLockOperation()); + } + + @Bean + ExternalReferencesOperation externalReferencesOperation() { + this.externalReferenceOperation = new ExternalReferencesOperation(titanDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper()); + GraphTestUtils.clearGraph(titanDao); + initGraphForTest(); + return this.externalReferenceOperation; + } + + @Bean + ToscaOperationFacade toscaOperationFacade(){ + Component componentMock = Mockito.mock(Component.class); + when(componentMock.getVersion()).thenReturn(VERSION); + when(componentMock.getUniqueId()).thenReturn(serviceVertexUuid); + List listComponents = new LinkedList(); + listComponents.add(componentMock); + when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents)); + when(toscaOperationFacadeMock.getComponentByUuidAndVersion(eq(serviceVertexUuid), eq(VERSION))).thenReturn(Either.left(componentMock)); + when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents.get(0))); + return toscaOperationFacadeMock; + } + + @Bean + IdMapper idMapper() { + IdMapper idMapper = Mockito.mock(IdMapper.class); + when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID); + when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID); + when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null); + return idMapper; + } + + @Bean + TopologyTemplateOperation topologyTemplateOperation() { + return new TopologyTemplateOperation(); + } + + @Bean + NodeTypeOperation nodeTypeOpertaion() { + return new NodeTypeOperation(null); + } + + @Bean + NodeTemplateOperation nodeTemplateOperation(){ + return new NodeTemplateOperation(); + } + + @Bean + GroupsOperation groupsOperation(){ + return new GroupsOperation(); + } + + @Bean + ICacheMangerOperation cacheMangerOperation() { return cacheManagerOperation; } + + @Bean + TitanDao titanDao() { + this.titanDao = new TitanDao(titanGraphClient()); + return titanDao; + } + + @Bean + TitanGraphClient titanGraphClient() { + return new TitanGraphClient(titanClientStrategy()); + } + + @Bean + TitanClientStrategy titanClientStrategy() { + return new DAOTitanStrategy(); + } + + @Bean + CategoryOperation categoryOperation(){ + return new CategoryOperation(); + } + + @Bean + GraphLockOperation graphLockOperation() { return graphLockOperation; } + + @Bean + TitanGenericDao titanGenericDao() { return titanGenericDao; } + + private void initGraphForTest() { + //create a service and add 1 ref + serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()); + serviceVertexUuid = this.serviceVertex.getUniqueId(); + + //monitoring references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3); + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + + //workflow references + externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6); + + final TitanOperationStatus commit = this.titanDao.commit(); + assertThat(commit).isEqualTo(TitanOperationStatus.OK); + } + + + } + + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + /* Users */ + private static User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(), System.currentTimeMillis()); + private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System.currentTimeMillis()); + private static User otherUser = new User("other", "other", "other", "other@email.com", Role.OPS.name(), System.currentTimeMillis()); + + + @BeforeClass + public static void setup() { + + //Needed for User Authorization + //======================================================================================================================== + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat); + when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value()); + + //Needed for error configuration + when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value()); + when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value()); + when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat); + when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat); + + when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + + Either adminEither = Either.left(adminUser); + Either designerEither = Either.left(designerUser); + Either otherEither = Either.left(otherUser); + + when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminEither); + when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerEither); + when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherEither); + //======================================================================================================================== + + //TODO DELETE after successfull merge + //if (ConfigurationManager.getConfigurationManager() == null) { + String appConfigDir = "src/test/resources/config"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + + org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration(); + configuration.setTitanInMemoryGraph(true); + + configurationManager.setConfiguration(configuration); + //} + ExternalConfiguration.setAppName("catalog-be"); + } + + @Before + public void beforeTest() { + + } + + @Test + public void testGetExternalRefsForExistingComponentInstance() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + List dto = response.readEntity(new GenericType>() { }); + assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testGetExternalRefsForAsset() { + String path = String.format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + Map> dtoMap = response.readEntity(new GenericType>>() { }); + assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testAddExternalRefForExistingComponentInstance(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value()); + + //Check that GET will include the new reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, adminUser.getUserId()). + get(); + + List dto = response.readEntity(new GenericType>() { }); + assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testDeleteExternalRefForExistingComponentInstance(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + //Verify that the deleted reference is returned in body + ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class); + assertThat(dto.getReferenceUUID()).isEqualTo(REF_5); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + + //Check that GET will NOT include the deleted reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + List getResponse = response.readEntity(new GenericType>() { }); + assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + @Test + public void testUpdateExternalRefForExistingComponentInstance(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + //Verify that the updated reference is returned in body + ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class); + assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + + //Check that GET will include the updated reference + response = target(). + path(getPath). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + + List dto = response.readEntity(new GenericType>() { }); + assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + } + + + /* + * Rainy Scenarios + */ + @Test + public void testAddExternalRefForNonExistingAssetId(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid", COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testAddExternalRefForNonExistingCompInstId(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, "FAKE_COM_ID", MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testAddExistingExternalRef(){ + String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE); + Response response = target(). + path(path). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + post(Entity.json(new ExternalRefDTO(REF_1))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned + } + + @Test + public void testUpdateExternalRefForNonExistingAssetId(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + //Verify that the 404 is returned + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + + } + + @Test + public void testUpdateExternalRefForNonExistingObjectIdOrOldRef(){ + String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5); + + Response response = target(). + path(updatePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + put(Entity.json(new ExternalRefDTO(REF_4))); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + System.out.println(response.readEntity(String.class)); + } + + @Test + public void testDeleteExternalRefForNonExistingAssetId(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testDeleteExternalRefForNonExistingRef(){ + String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF"); + Response response = target(). + path(deletePath). + request(MediaType.APPLICATION_JSON). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + delete(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + System.out.println(response.readEntity(String.class)); + } + + @Test + public void testGetExternalRefsForNonExistingAsset() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id", VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testGetExternalRefsForNonExistingVersion() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, designerUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + @Test + public void testGetExternalRefsForExistingComponentInstanceWithUnauthorizedUser() { + String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE); + + Response response = target(). + path(path). + request(). + accept(MediaType.APPLICATION_JSON). + header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId"). + header(Constants.USER_ID_HEADER, otherUser.getUserId()). + get(); + + assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(ExternalRefsServlet.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(request.getHeader(eq(Constants.X_ECOMP_INSTANCE_ID_HEADER))).thenReturn("mockXEcompInstIdHeader"); + when(session.getServletContext()).thenReturn(servletContext); + } + }) + .property("contextConfig", context); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java deleted file mode 100644 index 811a3031ae..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java +++ /dev/null @@ -1,288 +0,0 @@ -package org.openecomp.sdc.be.impl; - -import java.util.EnumMap; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdc.be.auditing.api.IAuditingManager; -import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.tosca.ToscaError; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; -import org.openecomp.sdc.exception.ResponseFormat; - -public class ComponentsUtilsTest { - - private ComponentsUtils createTestSubject() { - return new ComponentsUtils(); - } - - - @Test - public void testInit() throws Exception { - ComponentsUtils testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.Init(); - } - - - @Test - public void testGetAuditingManager() throws Exception { - ComponentsUtils testSubject; - IAuditingManager result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAuditingManager(); - } - - - @Test - public void testSetAuditingManager() throws Exception { - ComponentsUtils testSubject; - IAuditingManager auditingManager = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAuditingManager(auditingManager); - } - - - @Test - public void testAuditResource() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Resource resource = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - EnumMap additionalParams = null; - - // test 1 - testSubject = createTestSubject(); - actionEnum = null; - testSubject.auditResource(responseFormat, modifier, resource, prevState, prevVersion, actionEnum, - additionalParams); - } - - - @Test - public void testConvertFromStorageResponse() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = null; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponse(storageResponse); - } - - - @Test - public void testConvertFromStorageResponse_1() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = null; - ComponentTypeEnum type = null; - ActionStatus result; - - // test 1 - testSubject = createTestSubject(); - storageResponse = null; - result = testSubject.convertFromStorageResponse(storageResponse, type); - Assert.assertEquals(ActionStatus.GENERAL_ERROR, result); - } - - - @Test - public void testConvertFromToscaError() throws Exception { - ComponentsUtils testSubject; - ToscaError toscaError = null; - ActionStatus result; - - // test 1 - testSubject = createTestSubject(); - toscaError = null; - result = testSubject.convertFromToscaError(toscaError); - Assert.assertEquals(ActionStatus.GENERAL_ERROR, result); - } - - - @Test - public void testConvertFromStorageResponseForCapabilityType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForCapabilityType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForLifecycleType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForLifecycleType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForResourceInstance() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - boolean isRelation = false; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForResourceInstance(storageResponse, isRelation); - } - - - @Test - public void testConvertFromStorageResponseForResourceInstanceProperty() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForResourceInstanceProperty(storageResponse); - } - - - @Test - public void testAuditComponentAdmin() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Component component = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - ComponentTypeEnum type = null; - - // default test - testSubject = createTestSubject(); - testSubject.auditComponentAdmin(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type); - } - - - @Test - public void testAuditComponent() throws Exception { - ComponentsUtils testSubject; - ResponseFormat responseFormat = null; - User modifier = null; - Component component = null; - String prevState = ""; - String prevVersion = ""; - AuditingActionEnum actionEnum = null; - ComponentTypeEnum type = null; - EnumMap additionalParams = null; - - // test 1 - testSubject = createTestSubject(); - actionEnum = null; - testSubject.auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type, - additionalParams); - } - - - @Test - public void testValidateStringNotEmpty_1() throws Exception { - ComponentsUtils testSubject; - String value = ""; - Boolean result; - - // test 1 - testSubject = createTestSubject(); - value = null; - result = testSubject.validateStringNotEmpty(value); - Assert.assertEquals(false, result); - - // test 2 - testSubject = createTestSubject(); - value = ""; - result = testSubject.validateStringNotEmpty(value); - Assert.assertEquals(false, result); - } - - - @Test - public void testConvertFromStorageResponseForAdditionalInformation() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForAdditionalInformation(storageResponse); - } - - - @Test - public void testConvertFromResultStatusEnum() throws Exception { - ComponentsUtils testSubject; - ResultStatusEnum resultStatus = ResultStatusEnum.ELEMENT_NOT_FOUND; - JsonPresentationFields elementType = null; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromResultStatusEnum(resultStatus, elementType); - } - - - @Test - public void testConvertFromStorageResponseForConsumer() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForConsumer(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForGroupType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForGroupType(storageResponse); - } - - - @Test - public void testConvertFromStorageResponseForDataType() throws Exception { - ComponentsUtils testSubject; - StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND; - ActionStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.convertFromStorageResponseForDataType(storageResponse); - } - - - -} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java index cee856d905..be43fa7d62 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java @@ -20,9 +20,17 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; +import fj.data.Either; +import org.apache.commons.codec.binary.Base64; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.model.UploadResourceInfo; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import javax.ws.rs.core.Response; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -32,73 +40,60 @@ import java.nio.file.Paths; import java.util.Map; import java.util.stream.Stream; -import javax.ws.rs.core.Response; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; -import org.apache.commons.codec.binary.Base64; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.be.model.UploadResourceInfo; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.common.datastructure.Wrapper; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; +public class AbstractValidationsServletTest { + private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() {}; -import fj.data.Either; + private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s"; -public class AbstractValidationsServletTest { - private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() { - }; + @Before + public void setUp() throws Exception { + servlet.initLog(mock(Logger.class)); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetScarFromPayload() { - private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s"; + String payloadName = "valid_vf.csar"; + String rootPath = System.getProperty("user.dir"); + Path path = null; + byte[] data = null; + String payloadData = null; + Either, ResponseFormat> returnValue = null; + try { + path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar"); + data = Files.readAllBytes(path); + payloadData = Base64.encodeBase64String(data); + UploadResourceInfo resourceInfo = new UploadResourceInfo(); + resourceInfo.setPayloadName(payloadName); + resourceInfo.setPayloadData(payloadData); + Method privateMethod = null; + privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload", UploadResourceInfo.class); + privateMethod.setAccessible(true); + returnValue = (Either, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo); + } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + assertTrue(returnValue.isLeft()); + Map csar = returnValue.left().value(); + assertTrue(csar != null); + } - @Before - public void setUp() throws Exception { - servlet.initLog(mock(Logger.class)); - } + @Test + public void testValidToscaVersion() throws Exception { + Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion); + } - - @SuppressWarnings("unchecked") - @Test - public void testGetScarFromPayload() { - String payloadName = "valid_vf.csar"; - String rootPath = System.getProperty("user.dir"); - Path path = null; - byte[] data = null; - String payloadData = null; - Either, ResponseFormat> returnValue = null; - try { - path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar"); - data = Files.readAllBytes(path); - payloadData = Base64.encodeBase64String(data); - UploadResourceInfo resourceInfo = new UploadResourceInfo(); - resourceInfo.setPayloadName(payloadName); - resourceInfo.setPayloadData(payloadData); - Method privateMethod = null; - privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload", - UploadResourceInfo.class); - privateMethod.setAccessible(true); - returnValue = (Either, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo); - } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - } - assertTrue(returnValue.isLeft()); - Map csar = returnValue.left().value(); - assertTrue(csar != null); - } + private void testValidToscaVersion(String version) { + Wrapper responseWrapper = new Wrapper<>(); + servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(), String.format(BASIC_TOSCA_TEMPLATE, version)); + assertTrue(responseWrapper.isEmpty()); + } - @Test - public void testValidToscaVersion() throws Exception { - Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion); - } - private void testValidToscaVersion(String version) { - Wrapper responseWrapper = new Wrapper<>(); - servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(), - String.format(BASIC_TOSCA_TEMPLATE, version)); - assertTrue(responseWrapper.isEmpty()); - } - } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java index 6ef8091921..6fe303b495 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java @@ -20,42 +20,41 @@ package org.openecomp.sdc.be.servlets; -import java.util.HashSet; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Application; - import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.server.ResourceConfig; import org.mockito.Mockito; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Application; +import java.util.HashSet; +import java.util.Set; + public class ApplicationConfig extends Application { - public Set> getClasses() { - final Set> resources = new HashSet>(); + public Set> getClasses() { + final Set> resources = new HashSet>(); - // Add your resources. - resources.add(ResourceUploadServlet.class); - resources.add(MultiPart.class); - resources.add(FormDataContentDisposition.class); + // Add your resources. + resources.add(ResourceUploadServlet.class); + resources.add(MultiPart.class); + resources.add(FormDataContentDisposition.class); - final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - ResourceConfig resourceConfig = ResourceConfig.forApplication(this); + ResourceConfig resourceConfig = ResourceConfig.forApplication(this); - resourceConfig.register(new AbstractBinder() { + resourceConfig.register(new AbstractBinder() { - @Override - protected void configure() { - // TODO Auto-generated method stub - bind(request).to(HttpServletRequest.class); - } - }); + @Override + protected void configure() { + // TODO Auto-generated method stub + bind(request).to(HttpServletRequest.class); + } + }); - return resources; - } + return resources; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java new file mode 100644 index 0000000000..218505d8ef --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.servlets; + +import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.springframework.context.annotation.Bean; + +import static org.mockito.Mockito.mock; + +public class BaseTestConfig { + + @Bean + ComponentsUtils componentsUtils() {return new ComponentsUtils(mock(AuditingManager.class));} + + @Bean + DefaultExceptionMapper defaultExceptionMapper() {return new DefaultExceptionMapper();} + + @Bean + ComponentExceptionMapper componentExceptionMapper() { + return new ComponentExceptionMapper(componentsUtils()); + } + + @Bean + StorageExceptionMapper storageExceptionMapper() { + return new StorageExceptionMapper(componentsUtils()); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java index 97b1fe2a81..c723e0e664 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java @@ -1,17 +1,7 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.glassfish.grizzly.http.util.HttpStatus; +import fj.data.Either; +import org.eclipse.jetty.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; @@ -19,8 +9,8 @@ import org.glassfish.jersey.test.TestProperties; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -29,108 +19,114 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * The test suite designed for test functionality of ComponentInstanceServlet class */ public class ComponentInstanceServletTest extends JerseyTest { - - private final static String USER_ID = "jh0003"; - private static HttpServletRequest request; - private static HttpSession session; - private static ServletContext servletContext; - private static WebAppContextWrapper webAppContextWrapper; - private static WebApplicationContext webApplicationContext; - private static VFComponentInstanceBusinessLogic vfBusinessLogic; - private static ServiceComponentInstanceBusinessLogic serviceBusinessLogic; - private static ComponentsUtils componentsUtils; - private static ServletUtils servletUtils; - private static ResponseFormat responseFormat; - - @BeforeClass - public static void setup() { - createMocks(); - stubMethods(); - } - @Test - public void testGetRelationByIdSuccess(){ - - String containerComponentType = "resources"; - String componentId = "componentId"; - String relationId = "relationId"; - String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; - Either successResponse = Either.left(new RequirementCapabilityRelDef()); - when(vfBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse); - when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); - Response response = target() - .path(path) - .request(MediaType.APPLICATION_JSON) - .header("USER_ID", USER_ID) - .get( Response.class); + private final static String USER_ID = "jh0003"; + private static HttpServletRequest request; + private static HttpSession session; + private static ServletContext servletContext; + private static WebAppContextWrapper webAppContextWrapper; + private static WebApplicationContext webApplicationContext; + private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + + @BeforeClass + public static void setup() { + createMocks(); + stubMethods(); + } + + @Test + public void testGetRelationByIdSuccess(){ + + String containerComponentType = "resources"; + String componentId = "componentId"; + String relationId = "relationId"; + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; + Either successResponse = Either.left(new RequirementCapabilityRelDef()); + when(componentInstanceBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get( Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200); + } + + @Test + public void testGetRelationByIdFailure(){ + + String containerComponentType = "unknown_type"; + String componentId = "componentId"; + String relationId = "relationId"; + String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get( Response.class); - assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); - } - - @Test - public void testGetRelationByIdFailure(){ - - String containerComponentType = "unknown_type"; - String componentId = "componentId"; - String relationId = "relationId"; - String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId"; - when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); - when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat); - Response response = target() - .path(path) - .request(MediaType.APPLICATION_JSON) - .header("USER_ID", USER_ID) - .get( Response.class); + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400); + } - assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); - } + @Override + protected ResourceConfig configure() { + forceSet(TestProperties.CONTAINER_PORT, "0"); + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + return new ResourceConfig(ComponentInstanceServlet.class) + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + } - @Override - protected Application configure() { + private static void createMocks() { + request = Mockito.mock(HttpServletRequest.class); + session = Mockito.mock(HttpSession.class); + servletContext = Mockito.mock(ServletContext.class); + webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + webApplicationContext = Mockito.mock(WebApplicationContext.class); + componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class); + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + } - ResourceConfig resourceConfig = new ResourceConfig(ComponentInstanceServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - - resourceConfig.register(new AbstractBinder() { - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - return resourceConfig; - } - - private static void createMocks() { - request = Mockito.mock(HttpServletRequest.class); - session = Mockito.mock(HttpSession.class); - servletContext = Mockito.mock(ServletContext.class); - webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - webApplicationContext = Mockito.mock(WebApplicationContext.class); - vfBusinessLogic = Mockito.mock(VFComponentInstanceBusinessLogic.class); - serviceBusinessLogic = Mockito.mock(ServiceComponentInstanceBusinessLogic.class); - componentsUtils = Mockito.mock(ComponentsUtils.class); - servletUtils = Mockito.mock(ServletUtils.class); - responseFormat = Mockito.mock(ResponseFormat.class); - } - - private static void stubMethods() { - when(request.getSession()).thenReturn(session); - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(VFComponentInstanceBusinessLogic.class)).thenReturn(vfBusinessLogic); - when(webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class)).thenReturn(serviceBusinessLogic); - when(request.getHeader("USER_ID")).thenReturn(USER_ID); - when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); - when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); - } + private static void stubMethods() { + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ComponentInstanceBusinessLogic.class)).thenReturn(componentInstanceBusinessLogic); + when(request.getHeader("USER_ID")).thenReturn(USER_ID); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java new file mode 100644 index 0000000000..414ffaad59 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java @@ -0,0 +1,179 @@ +//package org.openecomp.sdc.be.servlets; +// +//import com.fasterxml.jackson.databind.DeserializationFeature; +//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +//import fj.data.Either; +//import org.eclipse.jetty.http.HttpStatus; +//import org.glassfish.hk2.utilities.binding.AbstractBinder; +//import org.glassfish.jersey.client.ClientConfig; +//import org.glassfish.jersey.server.ResourceConfig; +//import org.glassfish.jersey.test.JerseyTest; +//import org.glassfish.jersey.test.TestProperties; +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.mockito.Mock; +//import org.mockito.junit.MockitoJUnitRunner; +//import org.openecomp.sdc.be.DummyConfigurationManager; +//import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; +//import org.openecomp.sdc.be.dao.api.ActionStatus; +//import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +//import org.openecomp.sdc.be.impl.ComponentsUtils; +//import org.openecomp.sdc.be.impl.ServletUtils; +//import org.openecomp.sdc.be.impl.WebAppContextWrapper; +//import org.openecomp.sdc.be.info.GroupDefinitionInfo; +//import org.openecomp.sdc.be.model.GroupDefinition; +//import org.openecomp.sdc.common.api.Constants; +//import org.openecomp.sdc.exception.ResponseFormat; +//import org.springframework.web.context.WebApplicationContext; +// +//import javax.servlet.ServletContext; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpSession; +//import javax.ws.rs.client.ClientBuilder; +//import javax.ws.rs.client.Invocation; +//import javax.ws.rs.core.Application; +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.Response; +// +//import static org.assertj.core.api.Assertions.assertThat; +//import static org.junit.Assert.assertEquals; +//import static org.mockito.ArgumentMatchers.*; +//import static org.mockito.Mockito.when; +// +//@RunWith(MockitoJUnitRunner.class) +//public class GroupEndpointTest extends JerseyTest { +// +// public static final String USER_ID = "jh0003"; +// public static final String INVALID_USER_ID = "jh0001"; +// final static String RESOURCE_TYPE = "resources"; +// private static final String COMPONENT_ID = "1234"; +// private static final String VALID_GROUP_ID = "1"; +// private static final String INVALID_GROUP_ID = "2"; +// private static final String NEW_GROUP_NAME = "new group"; +// private static final String VALID_GROUP_TYPE = "networkConnection"; +// +// @Mock +// private GroupBusinessLogic groupBusinessLogic; +// @Mock +// private ServletContext servletContext; +// @Mock +// private WebAppContextWrapper webAppContextWrapper; +// @Mock +// private WebApplicationContext webApplicationContext; +// @Mock +// private HttpServletRequest request; +// @Mock +// private HttpSession session; +// @Mock +// private ComponentsUtils componentUtils; +// @Mock +// private ServletUtils servletUtils; +// @Mock +// private ResponseFormat responseFormat; +// +// @Override +// protected Application configure() { +// ResourceConfig resourceConfig = new ResourceConfig() +// .register(GroupServlet.class) +// //.register(mapper) +// ; +// forceSet(TestProperties.CONTAINER_PORT, "0"); +// resourceConfig.register(new AbstractBinder() { +// @Override +// protected void configure() { +// bind(request).to(HttpServletRequest.class); +// } +// }); +// return resourceConfig; +// } +// +// @Before +// public void before() { +// when(request.getSession()).thenReturn(session); +// when(session.getServletContext()).thenReturn(servletContext); +// when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); +// when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); +// when(webApplicationContext.getBean(GroupBusinessLogic.class)).thenReturn(groupBusinessLogic); +//// when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentUtils); +// when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); +// when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); +//// when(request.getHeader("USER_ID")).thenReturn(USER_ID); +// final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); +// setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider))); +// new DummyConfigurationManager(); +//// when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludePolicyTypesMap()); +// } +// +// //@Test +// public void createGroup() { +// GroupDefinition groupDefinition = new GroupDefinition(); +// groupDefinition.setName(NEW_GROUP_NAME); +// groupDefinition.setType(VALID_GROUP_TYPE); +// when(groupBusinessLogic.createGroup(eq(NEW_GROUP_NAME), eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(USER_ID))) +// .thenReturn(groupDefinition); +// //List gdList = buildCreateGroupCall().post(Response.class); +// +// } +// +// //@Test +// public void deleteGroup_withInvalidUser_shouldReturn_401() { +// int unauthorized401 = HttpStatus.UNAUTHORIZED_401; +// int unauthorized403 = HttpStatus.FORBIDDEN_403; +// when(groupBusinessLogic.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean())) +// .thenReturn(Either.right(new ResponseFormat(unauthorized401))); +// +// Response response = buildDeleteGroupCall(INVALID_USER_ID, VALID_GROUP_ID).delete(); +// assertThat(response.getStatus()).isEqualTo(unauthorized401); +// } +// +// @Test +// public void getGroupById_internalServerError() { +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.right(new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR_500))); +// Response response = buildGetGroupCall(VALID_GROUP_ID).get(); +// assertEquals(response.getStatus(), 500); +// } +// +// @Test +// public void getGroupById_Success() { +// GroupDefinitionInfo groupDefinitionInfo = new GroupDefinitionInfo(); +// groupDefinitionInfo.setUniqueId(VALID_GROUP_ID); +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.left(groupDefinitionInfo)); +// when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); +// when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200); +// GroupDefinitionInfo gdi = buildGetGroupCall(VALID_GROUP_ID).get(GroupDefinitionInfo.class); +// assertEquals(gdi.getUniqueId(), VALID_GROUP_ID); +// } +// +// @Test +// public void getGroupById_Failure() { +// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(INVALID_GROUP_ID), eq(USER_ID), eq(false) )) +// .thenReturn(Either.right(new ResponseFormat(HttpStatus.NOT_FOUND_404))); +// Response response = buildGetGroupCall(INVALID_GROUP_ID).get(); +// assertEquals(response.getStatus(), 404); +// } +// +// private Invocation.Builder buildGetGroupCall(String groupId) { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, USER_ID); +// } +// +// private Invocation.Builder buildDeleteGroupCall(String userId, String groupId) { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, userId); +// } +// +// private Invocation.Builder buildCreateGroupCall() { +// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups"; +// return target(path) +// .request(MediaType.APPLICATION_JSON) +// .header(Constants.USER_ID_HEADER, USER_ID); +// } +//} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java new file mode 100644 index 0000000000..2d5494354d --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java @@ -0,0 +1,197 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Sets; +import fj.data.Either; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.sdc.be.DummyConfigurationManager; +import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.utils.GroupTypeBuilder; +import org.openecomp.sdc.be.components.validation.UserValidations; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.GroupTypeDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class GroupTypesEndpointTest extends JerseySpringBaseTest { + + private static final String USER_ID = "a001"; + private static final String INVALID_USER_ID = "a002"; + private static final GroupTypeDefinition EMPTY_GROUP_TYPE = new GroupTypeDefinition(); + private static final String COMPONENT_TYPE = "VF"; + private static final HashSet EXCLUDED_TYPES = Sets.newHashSet("Root", "Heat"); + + private static ComponentsUtils componentsUtils; + private static GroupTypeOperation groupTypeOperation; + private static TitanDao titanDao; + private static UserValidations userValidations; + private static User user; + + @Configuration + @Import(BaseTestConfig.class) + static class GroupTypesTestConfig { + + @Bean + GroupTypesEndpoint groupTypesEndpoint() { + return new GroupTypesEndpoint(groupTypeBusinessLogic()); + } + + @Bean + GroupTypeBusinessLogic groupTypeBusinessLogic() { + return new GroupTypeBusinessLogic(groupTypeOperation, titanDao, userValidations); + } + } + + @BeforeClass + public static void initClass() { + componentsUtils = mock(ComponentsUtils.class); + groupTypeOperation = mock(GroupTypeOperation.class); + titanDao = mock(TitanDao.class); + userValidations = mock(UserValidations.class); + user = mock(User.class); + } + + @Before + public void init() { + new DummyConfigurationManager(); + when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludeGroupTypesMap()); + ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance(); + when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(Either.left(user)); + // TODO: handle for invalid user test +// when(userValidations.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean())).thenReturn(Either.right(???))); + } + + @Override + protected void configureClient(ClientConfig config) { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + config.register(jacksonJsonProvider); + } + + @Override + protected ResourceConfig configure() { + return super.configure(GroupTypesTestConfig.class) + .register(GroupTypesEndpoint.class); + } + + @Test + public void getGroupTypes_validUser_Success() { + List testConfigGroupTypes = buildGroupTypesList(); + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList()); + List fetchedGroupTypes = buildGetGroupTypesCall(USER_ID).get(new GenericType>(){}); + verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes); + } + + @Test + public void getGroupTypes_whenNoInteranlComponentType_passEmptyAsExcludedTypes() { + List testConfigGroupTypes = buildGroupTypesList(); + when(groupTypeOperation.getAllGroupTypes(null)).thenReturn(buildGroupTypesList()); + List fetchedGroupTypes = buildGetGroupTypesCallNoInternalComponent(USER_ID).get(new GenericType>(){}); + verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes); + } + + @Ignore + public void getGroupTypes_dbError() { + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenThrow(new StorageException(StorageOperationStatus.NOT_FOUND)); + when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)).thenReturn(ActionStatus.RESOURCE_NOT_FOUND); + when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND)).thenReturn(new ResponseFormat(HttpStatus.NOT_FOUND.value())); + Response response = buildGetGroupTypesCall(USER_ID).get(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); + } + + // TODO: simulate proper error with configuration error mapping and eactivate the test + @Ignore + public void getGroupTypes_invalidUser_Failure() { + when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList()); + Response response = buildGetGroupTypesCall(INVALID_USER_ID).get(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); + } + + private void verifyGroupTypesList(List groupTypes, List fetchedGroupTypes) { + assertThat(fetchedGroupTypes) + .usingElementComparatorOnFields("version", "type", "uniqueId") + .isEqualTo(groupTypes); + verifyOnlySpecificFieldsInResponse(fetchedGroupTypes, "version", "type", "uniqueId"); + } + + private void verifyOnlySpecificFieldsInResponse(List fetchedGroupTypes, String ... fields) { + assertThat(fetchedGroupTypes) + .usingElementComparatorIgnoringFields(fields) + .containsOnly(EMPTY_GROUP_TYPE); + } + + private Invocation.Builder buildGetGroupTypesCall(String userId) { + return target("/v1/catalog/groupTypes") + .queryParam("internalComponentType", COMPONENT_TYPE) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, userId); + } + + private Invocation.Builder buildGetGroupTypesCallNoInternalComponent(String userId) { + return target("/v1/catalog/groupTypes") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, userId); + } + + private Map> buildExcludeGroupTypesMap() { + return new ImmutableMap.Builder>() + .put("CR", Sets.newHashSet("VFModule", "Root", "Heat")) + .put(COMPONENT_TYPE, EXCLUDED_TYPES) + .build(); + } + + + private List buildGroupTypesList() { + GroupTypeDefinition type1 = GroupTypeBuilder.create() + .setDerivedFrom("root") + .setType("VFModule") + .setUniqueId("id1") + .setVersion("1.0") + .build(); + GroupTypeDefinition type2 = GroupTypeBuilder.create().setDerivedFrom("root").setType("Heat").setUniqueId("id2").build(); + return asList(type1, type2); + } + + private GroupTypeDefinition[] listOfEmptyGroupTypes(int size) { + return Stream.generate(GroupTypeDefinition::new).limit(size).toArray(GroupTypeDefinition[]::new); + } + + +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java new file mode 100644 index 0000000000..9a074c95c2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.be.servlets; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.BeforeClass; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import javax.servlet.http.HttpServletRequest; + +import static org.mockito.Mockito.mock; + +public class JerseySpringBaseTest extends JerseyTest { + + protected static HttpServletRequest request; + + @BeforeClass + public static void initBaseClass() { + request = mock(HttpServletRequest.class); + } + + protected ResourceConfig configure() { + return configure(BaseTestConfig.class); + } + + protected ResourceConfig configure(Class springConfig) { + ApplicationContext context = new AnnotationConfigApplicationContext(springConfig); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig() + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .register(DefaultExceptionMapper.class) + .register(ComponentExceptionMapper.class) + .register(StorageExceptionMapper.class) + .property("jersey.config.server.provider.classnames", "org.openecomp.sdc.be.view.MixinModelWriter") + .property("contextConfig", context); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java new file mode 100644 index 0000000000..bb949253b2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java @@ -0,0 +1,338 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import fj.data.Either; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +public class PolicyServletTest extends JerseySpringBaseTest{ + + private final static String USER_ID = "jh0003"; + private static final String COMPONENT_ID = "componentId"; + private static PolicyBusinessLogic businessLogic; + private static ComponentsUtils componentsUtils; + private static ServletUtils servletUtils; + private static ResponseFormat responseFormat; + + private static String validComponentType = "resources"; + private static String unsupportedComponentType = "unsupported"; + private static String componentId = "componentId"; + private static String policyTypeName = "policyTypeName"; + + private static final String PROPS_URL = "/v1/catalog/{componentType}/{serviceId}/policies/{policyId}/properties"; + private static final String SERVICE_ID = "serviceId"; + private static final String POLICY_ID = "policyId"; + + private static final String UPDATE_TARGETS_URL = "/v1/catalog/{componentType}/{componentId}/policies/{policyId}/targets"; + + @BeforeClass + public static void initClass() { + createMocks(); + when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils); + } + + @Before + public void beforeMethod() { + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider))); + } + + @Test + public void testGetPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + Either successResponse = Either.left(new PolicyDefinition()); + when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get(Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); + } + + @Test + public void testGetPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .get(Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testPostPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName; + PolicyDefinition policy = new PolicyDefinition(); + Either successResponse = Either.left(policy); + when(businessLogic.createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode()); + } + + @Test + public void testPostPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName; + PolicyDefinition policy = new PolicyDefinition(); + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testPutPolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + PolicyDefinition policy = new PolicyDefinition(); + policy.setUniqueId(POLICY_ID); + Either successResponse = Either.left(policy); + when(businessLogic.updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode()); + } + + @Test + public void testPutPolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + PolicyDefinition policy = new PolicyDefinition(); + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void testDeletePolicySuccess(){ + String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID; + Either successResponse = Either.left(new PolicyDefinition()); + when(businessLogic.deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true))).thenReturn(successResponse); + when(responseFormat.getStatus()).thenReturn(HttpStatus.NO_CONTENT_204.getStatusCode()); + when(componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .delete(Response.class); + + assertTrue(response.getStatus() == HttpStatus.NO_CONTENT_204.getStatusCode()); + } + + @Test + public void testDeletePolicyFailure(){ + String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID; + when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode()); + when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat); + Response response = target() + .path(path) + .request(MediaType.APPLICATION_JSON) + .header("USER_ID", USER_ID) + .delete(Response.class); + + assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode()); + } + + @Test + public void getPolicyProperties_operationForbidden() { + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.right(new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode()))); + Response response = buildGetPropertiesRequest().get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); + } + + @Test + public void getPolicyProperties_unHandledError_returnGeneralError() { + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenThrow(new RuntimeException()); + Response response = buildGetPropertiesRequest().get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test + @Ignore + public void getPolicyProperties_wrongComponentType() { + Response response = buildGetPropertiesRequest("unknownType").get(); + assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + verifyZeroInteractions(businessLogic); + } + + @Test + public void getPolicyProperties() { + List properties = getPropertiesList(); + when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.left(properties)); + List policyProps = buildGetPropertiesRequest().get(new GenericType>() {}); + assertThat(policyProps) + .usingElementComparatorOnFields("uniqueId") + .containsExactlyInAnyOrder(properties.get(0), properties.get(1)); + } + + @Test + public void updatePolicyPropertiesSuccess() { + List properties = getPropertiesList(); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.left(properties)); + List policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(new GenericType>() {}); + assertThat(policyProps) + .usingElementComparatorOnFields("uniqueId") + .containsExactlyInAnyOrder(properties.get(0), properties.get(1)); + } + + @Test + public void updatePolicyTargetsSuccess() { + List targets = getTargetDTOList(); + when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(Either.left(new PolicyDefinition())); + Response policyTargets = buildUpdateTargetsRequest(ComponentTypeEnum.RESOURCE_PARAM_NAME, targets).invoke(); + assertThat(policyTargets.getStatus()).isEqualTo(200); + } + + @Test + public void updatePolicyPropertiesFailure() { + List properties = getPropertiesList(); + ResponseFormat notFoundResponse = new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode()); + when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.right(notFoundResponse)); + Response policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(); + assertEquals(HttpStatus.NOT_FOUND_404.getStatusCode(), policyProps.getStatus()); + } + + private List getPropertiesList() { + PropertyDefinition prop1 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop1") + .build(); + + PropertyDefinition prop2 = new PropertyDataDefinitionBuilder() + .setUniqueId("prop2") + .build(); + return Arrays.asList(prop1, prop2); + } + + private List getTargetDTOList() { + PolicyTargetDTO target1 = new PolicyTargetDTO(); + target1.setUniqueIds(Collections.singletonList("uniqueId")); + target1.setType("GROUPS"); + + PolicyTargetDTO target2 = new PolicyTargetDTO(); + target2.setUniqueIds(Collections.singletonList("uniqueId")); + target2.setType("component_Instances"); + + return Arrays.asList(target1, target2); + } + + private Invocation.Builder buildGetPropertiesRequest(String componentType) { + return target(PROPS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + + } + + private Invocation buildUpdatePropertiesRequest(String componentType, List properties) { + return target(PROPS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON)); + } + + private Invocation buildUpdateTargetsRequest(String componentType, List targets) { + return target(UPDATE_TARGETS_URL) + .resolveTemplate("componentType", componentType) + .resolveTemplate("componentId", COMPONENT_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID) + .buildPut(Entity.entity(targets, MediaType.APPLICATION_JSON)); + } + + private Invocation.Builder buildGetPropertiesRequest() { + return target(PROPS_URL) + .resolveTemplate("componentType", "services") + .resolveTemplate("serviceId", SERVICE_ID) + .resolveTemplate("policyId", POLICY_ID) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + @Override + protected ResourceConfig configure() { + return super.configure() + .register(new PolicyServlet(businessLogic, servletUtils, null, componentsUtils)); + } + + private static void createMocks() { + businessLogic = Mockito.mock(PolicyBusinessLogic.class); + componentsUtils = Mockito.mock(ComponentsUtils.class); + servletUtils = Mockito.mock(ServletUtils.class); + responseFormat = Mockito.mock(ResponseFormat.class); + } + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java new file mode 100644 index 0000000000..23f32d169b --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.servlets; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import fj.data.Either; +import org.apache.http.HttpStatus; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider; +import org.glassfish.jersey.server.ResourceConfig; +import org.junit.Test; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PolicyTypesEndpointTest extends JerseySpringBaseTest { + + public static final String USER_ID = "userId"; + public static final String COMPONENT_TYPE = "VF"; + private PolicyTypeBusinessLogic policyTypeBusinessLogic; + private ComponentsUtils componentUtils; + + @Override + protected ResourceConfig configure() { + policyTypeBusinessLogic = mock(PolicyTypeBusinessLogic.class); + componentUtils = mock(ComponentsUtils.class); + final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + return super.configure() + .register(new PolicyTypesEndpoint(policyTypeBusinessLogic)) + .register(jacksonJsonProvider); + } + + @Test + public void getPolicyTypes() { + List policyTypes = buildPolicyTypesList(); + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.left(policyTypes)); + when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK)); + List fetchedPolicyTypes = buildGetPolicyTypesCall().get(new GenericType>(){}); + verifyPolicyTypesList(policyTypes, fetchedPolicyTypes); + } + + @Test + public void getPolicyTypes_whenNoInternalComponent_passNullAsComponentType() { + List policyTypes = buildPolicyTypesList(); + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, null)).thenReturn(Either.left(policyTypes)); + when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK)); + List fetchedPolicyTypes = buildGetPolicyTypesCallNoInternalComponent().get(new GenericType>(){}); + verifyPolicyTypesList(policyTypes, fetchedPolicyTypes); + } + + @Test + public void getPolicyTypes_error() { + when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.right(new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + Response response = buildGetPolicyTypesCall().get(); + assertThat(response.getStatus()).isEqualTo(500); + } + + private void verifyPolicyTypesList(List policyTypes, List fetchedPolicyTypes) { + assertThat(fetchedPolicyTypes) + .usingElementComparatorOnFields("version", "type", "uniqueId") + .isEqualTo(policyTypes); + assertThat(fetchedPolicyTypes).extracting("derivedFrom")//derivedFrom is not on the PolicyTypeMixin and should not return in response + .containsOnly((String)null); + } + + private Invocation.Builder buildGetPolicyTypesCall() { + return target("/v1/catalog/policyTypes") + .queryParam("internalComponentType", COMPONENT_TYPE) + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + private Invocation.Builder buildGetPolicyTypesCallNoInternalComponent() { + return target("/v1/catalog/policyTypes") + .request(MediaType.APPLICATION_JSON) + .header(Constants.USER_ID_HEADER, USER_ID); + } + + private List buildPolicyTypesList() { + PolicyTypeDefinition type1 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type1").setUniqueId("id1").setVersion("1.0").build(); + PolicyTypeDefinition type2 = new PolicyTypeBuilder().setDerivedFrom("type1").setType("type2").setUniqueId("id2").setVersion("1.0").build(); + PolicyTypeDefinition type3 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type3").setUniqueId("id3").setVersion("1.0").build(); + return asList(type1, type2, type3); + } + + + +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java index 7e0c6b7647..e8aeb5fc70 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java @@ -20,19 +20,9 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.Arrays; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.tuple.ImmutablePair; import org.glassfish.hk2.utilities.binding.AbstractBinder; @@ -46,6 +36,7 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; @@ -59,209 +50,217 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; -import fj.data.Either; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class ResourceServletTest extends JerseyTest { - public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); - final static HttpSession session = Mockito.mock(HttpSession.class); - final static ServletContext servletContext = Mockito.mock(ServletContext.class); - final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); - public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); - public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - when(request.getSession()).thenReturn(session); - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); - when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); - when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); - when(servletUtils.getUserAdmin()).thenReturn(userAdmin); - String userId = "jh0003"; - User user = new User(); - user.setUserId(userId); - user.setRole(Role.ADMIN.name()); - Either eitherUser = Either.left(user); - when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); - when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); - - ImmutablePair pair = new ImmutablePair(new Resource(), ActionStatus.OK); - Either, ResponseFormat> ret = Either.left(pair); - when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(ret); - - } - - @Before - public void beforeTest() { - Mockito.reset(componentUtils); - - Mockito.doAnswer(new Answer() { - public ResponseFormat answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - ActionStatus action = (ActionStatus) args[0]; - ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value()); - return resp; - } - }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class)); - - } - - @Test - public void testHappyScenarioTest() { - UploadResourceInfo validJson = buildValidJson(); - setMD5OnRequest(true, validJson); - Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK); - assertTrue(response.getStatus() == HttpStatus.CREATED.value()); - - } - - @Test - public void testNonValidMd5Fail() { - UploadResourceInfo validJson = buildValidJson(); - - setMD5OnRequest(false, validJson); - - Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); - assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); - - } - - @Test - public void testNonValidPayloadNameFail() { - UploadResourceInfo mdJson = buildValidJson(); - mdJson.setPayloadName("myCompute.xml"); - - runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION); - - } - - @Test - public void testNullPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - mdJson.setPayloadData(null); - runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD); - - } - - @Test - public void testNonYmlPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - String payload = "{ json : { isNot : yaml } "; - encodeAndSetPayload(mdJson, payload); - runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE); - - } - - @Test - public void testNonToscaPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - - String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; - encodeAndSetPayload(mdJson, payload); - runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE); - - } - - @Test - public void testServiceToscaPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - - String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n" - + " description: update update"; - - encodeAndSetPayload(mdJson, payload); - runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); - - } - - @Test - public void testMultipleResourcesInPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - - String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n" - + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; - - encodeAndSetPayload(mdJson, payload); - runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE); - - } - - @Test - public void testNonValidNameSpaceInPayloadFail() { - UploadResourceInfo mdJson = buildValidJson(); - - String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; - - encodeAndSetPayload(mdJson, payload); - runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE); - - } - - private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) { - byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes()); - mdJson.setPayloadData(new String(encodedBase64Payload)); - } - - private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) { - setMD5OnRequest(true, mdJson); - Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); - Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload); - assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); - } - - private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) { - String md5 = (isValid) ? GeneralUtility.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam="; - when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class); + final static HttpSession session = Mockito.mock(HttpSession.class); + final static ServletContext servletContext = Mockito.mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + + ImmutablePair pair = new ImmutablePair(new Resource(), ActionStatus.OK); + Either, ResponseFormat> ret = Either.left(pair); + when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(ret); + + } + + @Before + public void beforeTest() { + Mockito.reset(componentUtils); + + Mockito.doAnswer(new Answer() { + public ResponseFormat answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + ActionStatus action = (ActionStatus) args[0]; + ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value()); + return resp; + } + }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class)); + + } + + @Test + public void testHappyScenarioTest() { + UploadResourceInfo validJson = buildValidJson(); + setMD5OnRequest(true, validJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK); + assertTrue(response.getStatus() == HttpStatus.CREATED.value()); + + } + + @Test + public void testNonValidMd5Fail() { + UploadResourceInfo validJson = buildValidJson(); + + setMD5OnRequest(false, validJson); + + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + + } + + @Test + public void testNonValidPayloadNameFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadName("myCompute.xml"); + + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION); + + } + + @Test + public void testNullPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + mdJson.setPayloadData(null); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD); + + } + + @Test + public void testNonYmlPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + String payload = "{ json : { isNot : yaml } "; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE); + + } + + @Test + public void testNonToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE); + + } + + @Test + public void testServiceToscaPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " topology_template: thisIsService\r\n" + + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE); + + } + + @Test + public void testMultipleResourcesInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n" + + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE); + + } + + @Test + public void testNonValidNameSpaceInPayloadFail() { + UploadResourceInfo mdJson = buildValidJson(); + + String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update"; + + encodeAndSetPayload(mdJson, payload); + runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE); + + } + + private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) { + byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes()); + mdJson.setPayloadData(new String(encodedBase64Payload)); + } + + private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) { + setMD5OnRequest(true, mdJson); + Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class)); + Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload); + assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()); + } - } + private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) { + String md5 = (isValid) ? GeneralUtility.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam="; + when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5); + + } - private UploadResourceInfo buildValidJson() { - UploadResourceInfo ret = new UploadResourceInfo(); - ret.setName("ciMyCompute"); - ret.setPayloadName("ciMyCompute.yml"); - ret.addSubCategory("Application Layer 4+", "Application Servers"); - ret.setDescription("ResourceDescription"); - ret.setVendorName("VendorName"); - ret.setVendorRelease("VendorRelease"); - ret.setContactId("AT1234"); - ret.setIcon("router"); - ret.setTags(Arrays.asList(new String[] { "ciMyCompute" })); - ret.setPayloadData( - "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); - return ret; - } - - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(ResourcesServlet.class); - forceSet(TestProperties.CONTAINER_PORT, "0"); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } + private UploadResourceInfo buildValidJson() { + UploadResourceInfo ret = new UploadResourceInfo(); + ret.setName("ciMyCompute"); + ret.setPayloadName("ciMyCompute.yml"); + ret.addSubCategory("Application Layer 4+", "Application Servers"); + ret.setDescription("ResourceDescription"); + ret.setVendorName("VendorName"); + ret.setVendorRelease("VendorRelease"); + ret.setContactId("AT1234"); + ret.setIcon("router"); + ret.setTags(Arrays.asList(new String[] { "ciMyCompute" })); + ret.setPayloadData( + "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl"); + return ret; + } + + @Override + protected Application configure() { + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + forceSet(TestProperties.CONTAINER_PORT, "0"); + return new ResourceConfig(ResourcesServlet.class) + .register(new AbstractBinder() { + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }) + .property("contextConfig", context); + + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java index ff69241263..23daab9bf9 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java @@ -20,25 +20,7 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.ArgumentMatchers.anyObject; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletContext; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.FormDataBodyPart; @@ -53,6 +35,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.UploadResourceInfo; @@ -64,125 +47,105 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; public class ResourceUploadServletTest extends JerseyTest { - private static Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class.getName()); - final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - final HttpSession session = Mockito.mock(HttpSession.class); - final ServletContext servletContext = Mockito.mock(ServletContext.class); - final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class); - final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class); - - Gson gson = new Gson(); - - public void zipDirectory() { - - } - - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader); - when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK); - when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager); - } - - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(ResourceUploadServlet.class); - - resourceConfig.register(MultiPartFeature.class); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - // The below code was cut-pasted to here from setup() because - // due to it now has - // to be executed during servlet initialization - bind(request).to(HttpServletRequest.class); - when(request.getSession()).thenReturn(session); - when(session.getServletContext()).thenReturn(servletContext); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { - - when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); - - } - - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - } - }); - - return resourceConfig; - } - - @Override - protected void configureClient(ClientConfig config) { - config.register(MultiPartFeature.class); - } - - public class DelegatingServletInputStream extends ServletInputStream { - - private final InputStream sourceStream; - - /** - * Create a DelegatingServletInputStream for the given source stream. - * - * @param sourceStream - * the source stream (never null) - */ - public DelegatingServletInputStream(InputStream sourceStream) { - // Assert.notNull(sourceStream, - // "Source InputStream must not be null"); - this.sourceStream = sourceStream; - } - - /** - * Return the underlying source stream (never null). - */ - public final InputStream getSourceStream() { - return this.sourceStream; - } - - public int read() throws IOException { - return this.sourceStream.read(); - } - - public void close() throws IOException { - super.close(); - this.sourceStream.close(); - } - - } - - @Test - public void testMultipart() { - FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip")); - - List tags = new ArrayList(); - tags.add("tag1"); - tags.add("tag2"); - UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null); - - FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE); - MultiPart multipartEntity = new FormDataMultiPart(); - multipartEntity.bodyPart(filePart); - multipartEntity.bodyPart(metadataPart); - - Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); - log.debug("{}", response); - } + private static final Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpSession session = Mockito.mock(HttpSession.class); + final ServletContext servletContext = Mockito.mock(ServletContext.class); + final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class); + final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class); + + Gson gson = new Gson(); + + public void zipDirectory() { + + } + + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader); + when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK); + when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager); + } + + @Override + protected Application configure() { + + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + return new ResourceConfig(ResourceUploadServlet.class) + .register(MultiPartFeature.class) + .register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }) + .property("contextConfig", context); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @Test + public void testMultipart() { + FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip")); + List tags = new ArrayList(); + tags.add("tag1"); + tags.add("tag2"); + UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null); + + FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + multipartEntity.bodyPart(metadataPart); + + Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + log.debug("{}", response); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java index 37a493de37..690f7427a8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java @@ -20,22 +20,8 @@ package org.openecomp.sdc.be.servlets; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.glassfish.grizzly.http.util.HttpStatus; +import fj.data.Either; +import org.eclipse.jetty.http.HttpStatus; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.FormDataMultiPart; @@ -49,6 +35,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager; import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.config.SpringConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; @@ -62,182 +49,109 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.context.WebApplicationContext; -import fj.data.Either; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; public class TypesUploadServletTest extends JerseyTest { - public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - public static final HttpSession session = Mockito.mock(HttpSession.class); - public static final ServletContext servletContext = Mockito.mock(ServletContext.class); - public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); - public static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class); - public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); - public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); - public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); - public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)) - .thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager); - when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); - when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); - when(servletUtils.getUserAdmin()).thenReturn(userAdmin); - String userId = "jh0003"; - User user = new User(); - user.setUserId(userId); - user.setRole(Role.ADMIN.name()); - Either eitherUser = Either.left(user); - when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); - when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); - when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode()); - when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); - - } - - @Test - public void creatingCapabilityTypeSuccessTest() { - List emptyList = new ArrayList(); - Either, ResponseFormat> either = Either.left(emptyList); - when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either); - FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", - new File("src/test/resources/types/capabilityTypes.zip")); - MultiPart multipartEntity = new FormDataMultiPart(); - multipartEntity.bodyPart(filePart); - - Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON) - .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); - - assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode()); - - } - - @Override - protected void configureClient(ClientConfig config) { - config.register(MultiPartFeature.class); - } - - @Override - protected Application configure() { - ResourceConfig resourceConfig = new ResourceConfig(TypesUploadServlet.class); - - resourceConfig.register(MultiPartFeature.class); - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - // The below code was cut-pasted to here from setup() because - // due to it now has - // to be executed during servlet initialization - bind(request).to(HttpServletRequest.class); - when(request.getSession()).thenReturn(session); - when(session.getServletContext()).thenReturn(servletContext); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource( - ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { - - when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); - - } - - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .thenReturn(configurationManager); - } - }); - - return resourceConfig; - } - - private TypesUploadServlet createTestSubject() { - return new TypesUploadServlet(); - } - - - @Test - public void testUploadCapabilityType() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadInterfaceLifecycleType() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadCategories() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadDataTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadGroupTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUploadPolicyTypes() throws Exception { - TypesUploadServlet testSubject; - File file = null; - HttpServletRequest request = null; - String creator = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - + public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + private static final HttpSession session = Mockito.mock(HttpSession.class); + public static final ServletContext servletContext = Mockito.mock(ServletContext.class); + public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); + private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class); + private static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class); + private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class); + private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class); + private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class); + private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager); + when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils); + when(servletUtils.getComponentsUtils()).thenReturn(componentUtils); + when(servletUtils.getUserAdmin()).thenReturn(userAdmin); + String userId = "jh0003"; + User user = new User(); + user.setUserId(userId); + user.setRole(Role.ADMIN.name()); + Either eitherUser = Either.left(user); + when(userAdmin.getUser(userId, false)).thenReturn(eitherUser); + when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId); + when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201); + when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat); + + } + + @Test + public void creatingCapabilityTypeSuccessTest() { + List emptyList = new ArrayList(); + Either, ResponseFormat> either = Either.left(emptyList); + when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either); + FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", new File("src/test/resources/types/capabilityTypes.zip")); + MultiPart multipartEntity = new FormDataMultiPart(); + multipartEntity.bodyPart(filePart); + + Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class); + + assertTrue(response.getStatus() == HttpStatus.CREATED_201); + + } + + @Override + protected void configureClient(ClientConfig config) { + config.register(MultiPartFeature.class); + } + + @Override + protected ResourceConfig configure() { + + ResourceConfig resourceConfig = new ResourceConfig() + .register(new TypesUploadServlet(importManager, null, null, null, null, null)); + + resourceConfig.register(MultiPartFeature.class); + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + // The below code was cut-pasted to here from setup() because + // due to it now has + // to be executed during servlet initialization + bind(request).to(HttpServletRequest.class); + when(request.getSession()).thenReturn(session); + when(session.getServletContext()).thenReturn(servletContext); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) { + + when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader); + + } + + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + } + }); + ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); + resourceConfig.property("contextConfig", context); + + return resourceConfig; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java index afa0907f25..696214f49d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java @@ -20,24 +20,13 @@ package org.openecomp.sdc.be.servlets; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.Response; - +import com.google.gson.Gson; +import fj.data.Either; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Test; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; @@ -52,238 +41,105 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; -import com.google.gson.Gson; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Application; -import fj.data.Either; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; public class UserAdminServletTest extends JerseyTest { - final static HttpServletRequest request = mock(HttpServletRequest.class); - final static HttpSession session = mock(HttpSession.class); - final static ServletContext servletContext = mock(ServletContext.class); - final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class); - final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class); - final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class); - final static AuditingManager auditingManager = mock(AuditingManager.class); - final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class); - final static ResponseFormat okResponseFormat = mock(ResponseFormat.class); - - final static String ADMIN_ATT_UID = "jh0003"; - Gson gson = new Gson(); - - @BeforeClass - public static void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - when(session.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)) - .thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); - - when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager); - when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils); - when(componentsUtils.getAuditingManager()).thenReturn(auditingManager); - when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat); - when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value()); - - } - - @Before - public void beforeTest() { - reset(userAdminManager); - doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false); - - reset(request); - when(request.getSession()).thenReturn(session); - when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID); - } - - /* - * @Test public void deactivateUserSuccessfullyTest(){ String - * userToDeleteUserId = "admin1"; User adminUser = new User(); - * adminUser.setUserId(ADMIN_ATT_UID); Either - * eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User - * userToDelete = eitherActiveUser.left().value(); - * doReturn(eitherActiveUser).when(userAdminManager).getUser( - * userToDeleteUserId); - * - * Either eitherInactiveUser = - * buildEitherUser(userToDeleteUserId, false); - * doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser( - * adminUser, userToDelete.getUserId()); - * - * - * Response response = - * target().path("/v1/user/"+userToDeleteUserId).request().delete(); - * assertTrue(response.getStatus() == HttpStatus.OK.value()); - * verify(userAdminManager, times(1)).deActivateUser(adminUser, - * userToDelete.getUserId()); } - * - * - * @Test public void forceDeleteUserSuccessfullyTest(){ String - * userToDeleteUserId = "admin1"; - * when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User. - * FORCE_DELETE_HEADER_FLAG); - * - * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); - * - * Either eitherActiveUser = - * buildEitherUser(userToDeleteUserId, true); User userToDelete = - * eitherActiveUser.left().value(); - * doReturn(eitherActiveUser).when(userAdminManager).getUser( - * userToDeleteUserId); - * - * Either eitherUser = - * buildEitherUser(userToDeleteUserId, true); - * doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete. - * getUserId()); - * - * - * Response response = - * target().path("/v1/user/"+userToDeleteUserId).request().delete(); - * assertTrue(response.getStatus() == HttpStatus.OK.value()); - * verify(userAdminManager, times(0)).deActivateUser(adminUser, - * userToDelete.getUserId()); verify(userAdminManager, - * times(1)).deleteUser(userToDelete.getUserId()); } - */ - - @Override - protected Application configure() { - - ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class); - - resourceConfig.register(new AbstractBinder() { - - @Override - protected void configure() { - bind(request).to(HttpServletRequest.class); - } - }); - - return resourceConfig; - } - - private static Either buildEitherUser(String userId, boolean isActive) { - User user = new User(); - user.setUserId(userId); - user.setRole(UserRoleEnum.ADMIN.getName()); - if (!isActive) { - user.setStatus(UserStatusEnum.INACTIVE); - } - return Either.left(user); - } - - private UserAdminServlet createTestSubject() { - return new UserAdminServlet(); - } - - - @Test - public void testGet() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetRole() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUpdateUserRole() throws Exception { - UserAdminServlet testSubject; - String userIdUpdateUser = ""; - HttpServletRequest request = null; - String data = ""; - String modifierUserId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testCreateUser() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String newUserData = ""; - String modifierAttId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testAuthorize() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String userId = ""; - String firstName = ""; - String lastName = ""; - String email = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetAdminsUser() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetUsersList() throws Exception { - UserAdminServlet testSubject; - HttpServletRequest request = null; - String userId = ""; - String roles = ""; - Response result; - - // test 1 - testSubject = createTestSubject(); - roles = null; - - // test 2 - testSubject = createTestSubject(); - roles = ""; - } - - - @Test - public void testDeActivateUser() throws Exception { - UserAdminServlet testSubject; - String userId = ""; - HttpServletRequest request = null; - String userIdHeader = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } + final static HttpServletRequest request = mock(HttpServletRequest.class); + final static HttpSession session = mock(HttpSession.class); + final static ServletContext servletContext = mock(ServletContext.class); + final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class); + final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class); + final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class); + final static AuditingManager auditingManager = mock(AuditingManager.class); + final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class); + final static ResponseFormat okResponseFormat = mock(ResponseFormat.class); + + final static String ADMIN_ATT_UID = "jh0003"; + Gson gson = new Gson(); + + @BeforeClass + public static void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + when(session.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); + when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext); + + when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager); + when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils); + when(componentsUtils.getAuditingManager()).thenReturn(auditingManager); + when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat); + when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value()); + + } + + @Before + public void beforeTest() { + reset(userAdminManager); + doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false); + + reset(request); + when(request.getSession()).thenReturn(session); + when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID); + } + + /* + * @Test public void deactivateUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); Either eitherActiveUser = buildEitherUser(userToDeleteUserId, true); + * User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either eitherInactiveUser = buildEitherUser(userToDeleteUserId, false); doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser( adminUser, userToDelete.getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(1)).deActivateUser(adminUser, userToDelete.getUserId()); } + * + * + * @Test public void forceDeleteUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User. FORCE_DELETE_HEADER_FLAG); + * + * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); + * + * Either eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId); + * + * Either eitherUser = buildEitherUser(userToDeleteUserId, true); doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete. getUserId()); + * + * + * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(0)).deActivateUser(adminUser, userToDelete.getUserId()); + * verify(userAdminManager, times(1)).deleteUser(userToDelete.getUserId()); } + */ + + @Override + protected Application configure() { + + ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class); + + resourceConfig.register(new AbstractBinder() { + + @Override + protected void configure() { + bind(request).to(HttpServletRequest.class); + } + }); + + return resourceConfig; + } + + private static Either buildEitherUser(String userId, boolean isActive) { + User user = new User(); + user.setUserId(userId); + user.setRole(UserRoleEnum.ADMIN.getName()); + if (!isActive) { + user.setStatus(UserStatusEnum.INACTIVE); + } + return Either.left(user); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java new file mode 100644 index 0000000000..3c42257446 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.be.tosca; +// + +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; + +public class CapabiltyRequirementConvertorTest { + + CapabiltyRequirementConvertor capabiltyRequirementConvertor = Mockito.spy(new CapabiltyRequirementConvertor()); + ComponentInstance instanceProxy = Mockito.spy( new ComponentInstance() ); + ComponentInstance vfInstance = Mockito.spy( new ComponentInstance() ); + Component vfComponent = Mockito.spy( new Resource() ); + ComponentInstance vfcInstance = Mockito.spy( new ComponentInstance() ); + Component vfcComponent = Mockito.spy( new Resource() ); + + @Test + public void getReducedPathByOwner() throws Exception { + List pathList = new ArrayList<>(); + String uniqueId = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_2"; + + String exerpt = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"; + String duplicate = "a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"; + pathList.add(exerpt); + pathList.add(duplicate); + pathList.add(duplicate); + pathList.add(uniqueId); + + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + List reducedMap = new CapabiltyRequirementConvertor().getReducedPathByOwner( pathList , uniqueId ); + + assertThat( reducedMap ).isNotNull().doesNotContain(exerpt).containsOnlyOnce(duplicate).hasSize(4); + } + + //generate stub capability + private Map> newCapabilities(String capabilityName){ + Map> capabilities = new HashMap<>(); + List list = new ArrayList<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setName( capabilityName ); + capabilityDefinition.setType("att.Node"); + List pathList = new ArrayList<>(); + + capabilityDefinition.setOwnerId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693"); + pathList.add("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + //pathList.add("a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"); + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + capabilityDefinition.setPath(pathList); + list.add(capabilityDefinition); + capabilities.put(capabilityDefinition.getType() , list ); + + return capabilities; + } + + + @Test + public void testBuildName(){ + doReturn("1").when(instanceProxy).getActualComponentUid(); + doReturn("2").when(vfInstance).getActualComponentUid(); + doReturn("3").when(vfcInstance).getActualComponentUid(); + //region proxy + Component proxyOrigin = new Resource(); + + proxyOrigin.setName( "vepdgtp4837svc_proxy0" ); + proxyOrigin.setComponentType(ComponentTypeEnum.RESOURCE); + proxyOrigin.setComponentInstances( asList( vfInstance ) ); + + //endregion + //region vf+vfc + vfInstance.setName("vepdgtp4837vf0"); + vfInstance.setNormalizedName("vepdgtp4837vf0"); + vfInstance.setUniqueId("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + vfComponent.setName("vepdgtp4837vf0"); //origin + vfComponent.setComponentInstances(Arrays.asList(vfcInstance)); + vfcInstance.setUniqueId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcInstance.setName("lb_1"); + vfcInstance.setNormalizedName("lb_1"); + vfcInstance.setName("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcComponent.setName("lb_1"); + //endregion + Map> capabilities = newCapabilities("port"); + vfcComponent.setCapabilities(capabilities); + Map map = Collections.unmodifiableMap(new HashMap() { + { + put( proxyOrigin, null ); + put( vfComponent, vfInstance ); + put( vfcComponent, vfcInstance ); + } } ) ; + Map cache = Collections.unmodifiableMap(new HashMap() {{ + put( "1",proxyOrigin); + put( "2" ,vfComponent); + put( "3" ,vfcComponent); + }}); + instanceProxy.setCapabilities(capabilities); + proxyOrigin.setCapabilities( capabilities ); + List flatList = capabilities.values().stream().flatMap(List::stream).collect(Collectors.toList()); + flatList.stream().forEach( (CapabilityDefinition capabilityDefinition) -> { + String name = capabiltyRequirementConvertor.buildCapabilityNameForComponentInstance(cache, instanceProxy, capabilityDefinition); + System.out.println("built name -> " + name); + assertThat(name).isEqualTo( "vepdgtp4837vf0.lb_1."+capabilityDefinition.getName() ); + }); + } +} + diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java index 7348156923..8883786d7e 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java @@ -20,116 +20,71 @@ package org.openecomp.sdc.be.tosca; -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.Assert; +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; import org.openecomp.sdc.common.api.ConfigurationSource; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; -import fj.data.Either; - -public class CsarUtilsTest { - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - // Init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), - appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } - - @Test - public void testValidateNonMetaArtifactHappyScenario() { - String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map>> collectedWarningMessages = new HashMap<>(); - Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - assertTrue(collectedWarningMessages.isEmpty()); - - artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - assertTrue(collectedWarningMessages.isEmpty()); - } - - @Test - public void testValidateNonMetaArtifactScenarioWithWarnnings() { - String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map>> collectedWarningMessages = new HashMap<>(); - Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - - artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft()); - - assertTrue(collectedWarningMessages.size() == 1); - assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); - } - - @Test - public void testValidateNonMetaArtifactUnhappyScenario() { - String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map>> collectedWarningMessages = new HashMap<>(); - Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, - payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isRight()); - assertTrue(!collectedWarningMessages.isEmpty()); - } - - private CsarUtils createTestSubject() { - return new CsarUtils(); - } - - - @Test - public void testExtractVfcsArtifactsFromCsar() throws Exception { - Map csar = null; - Map> result; - - // test 1 - csar = null; - result = CsarUtils.extractVfcsArtifactsFromCsar(csar); - Assert.assertEquals(new HashMap>() , result); - } - - - @Test - public void testHandleWarningMessages() throws Exception { - Map>> collectedWarningMessages = new HashMap<>(); - - // default test - CsarUtils.handleWarningMessages(collectedWarningMessages); - } - - - @Test - public void testValidateNonMetaArtifact() throws Exception { - String artifactPath = ""; - byte[] payloadData = new byte[] { ' ' }; - Map>> collectedWarningMessages = null; - Either result; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; - // default test - result = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - } +import static org.junit.Assert.assertTrue; +public class CsarUtilsTest { + @Before + public void setup() { + ExternalConfiguration.setAppName("catalog-be"); + + // init Configuration + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); + } + + @Test + public void testValidateNonMetaArtifactHappyScenario(){ + String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map>> collectedWarningMessages = new HashMap<>(); + Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + assertTrue(collectedWarningMessages.isEmpty() ); + + artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + assertTrue(collectedWarningMessages.isEmpty() ); + } + + @Test + public void testValidateNonMetaArtifactScenarioWithWarnnings(){ + String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map>> collectedWarningMessages = new HashMap<>(); + Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + + artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft() ); + + assertTrue(collectedWarningMessages.size() == 1 ); + assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); + } + + @Test + public void testValidateNonMetaArtifactUnhappyScenario(){ + String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map>> collectedWarningMessages = new HashMap<>(); + Either eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isRight() ); + assertTrue( !collectedWarningMessages.isEmpty() ); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java index 139de137d9..dbdec12193 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java @@ -1,18 +1,6 @@ package org.openecomp.sdc.be.tosca; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; @@ -23,7 +11,18 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.tosca.model.ToscaNodeType; import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; public class PropertyConvertorTest { private PropertyDefinition property; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java index acfeaf1abc..839095f1ca 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.be.tosca; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; import java.io.FileInputStream; import java.io.IOException; @@ -31,46 +31,46 @@ import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; -import org.yaml.snakeyaml.Yaml; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class SchemaFiles { - - @Test - public void testValidateYamlNormativeFiles(){ - String importToscaPath = "src/main/resources/import/tosca"; - assertTrue(checkValidYamlInFileTree(importToscaPath)); - } - - @Test - public void testRainyYamlNormativeFiles(){ - String importToscaPathTest = "src/test/resources/yamlValidation"; - assertFalse(checkValidYamlInFileTree(importToscaPathTest)); - } - - private boolean checkValidYamlInFileTree(String fileTree) { - - try { - List fileTreeYamlList = Files.walk(Paths.get(fileTree)) - .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml")) - .collect(Collectors.toList()); - - for (Path yamlFile : fileTreeYamlList) { - try { - FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString()); - Yaml yaml = new Yaml(); - Object content = yaml.load(inputStream); - } catch (Exception e) { - System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString()); - return false; - } - } - } catch (IOException e) { - System.out.println("Error in reading file from folder : " + fileTree); - return false; - } - return true; - } - - + + @Test + public void testValidateYamlNormativeFiles(){ + String importToscaPath = "src/main/resources/import/tosca"; + assertTrue(checkValidYamlInFileTree(importToscaPath)); + } + + @Test + public void testRainyYamlNormativeFiles(){ + String importToscaPathTest = "src/test/resources/yamlValidation"; + assertFalse(checkValidYamlInFileTree(importToscaPathTest)); + } + + private boolean checkValidYamlInFileTree(String fileTree) { + + try { + List fileTreeYamlList = Files.walk(Paths.get(fileTree)) + .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml")) + .collect(Collectors.toList()); + + for (Path yamlFile : fileTreeYamlList) { + try { + FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString()); + Yaml yaml = new Yaml(); + Object content = yaml.load(inputStream); + } catch (Exception e) { + System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString()); + return false; + } + } + } catch (IOException e) { + System.out.println("Error in reading file from folder : " + fileTree); + return false; + } + return true; + } + + } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java index 4c22cf3599..efc89a9f9d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java @@ -1,124 +1,120 @@ package org.openecomp.sdc.be.tosca; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - public class ToscaExportUtilsTest { - private static Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class.getName()); - @javax.annotation.Resource - private VFComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @javax.annotation.Resource - private ServiceComponentInstanceBusinessLogic serviceInstanceBusinessLogic; - @Autowired - private ToscaExportHandler exportUtils; - @Autowired - private ComponentInstanceOperation componentInstanceOperation; - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @Test - public void testExportService() { - /* Resource resource1 = ResourceTestUtils.prepareResource(0); - resource1.setResourceType(ResourceTypeEnum.VF); - Either createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null); - assertTrue(createResource1.isLeft()); - Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value()); - - Resource resource2 = ResourceTestUtils.prepareResource(1); - resource2.setResourceType(ResourceTypeEnum.VF); - Either createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null); - assertTrue(createResource2.isLeft()); - Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value()); - - Service service = ResourceTestUtils.prepareService(0); - Either createService = serviceBusinessLogic.createService(service, getAdminUser()); - assertTrue(createService.isLeft()); - - // add VFC instance to VF - ComponentInstance vfcResourceInstance1 = new ComponentInstance(); - vfcResourceInstance1.setDescription("VFC instance 1"); - vfcResourceInstance1.setName(certifiedVFC1.getName()); - vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId()); - - Either createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance1); - assertTrue(createResourceVfcInstance1.isLeft()); - - ComponentInstance vfcResourceInstance2 = new ComponentInstance(); - vfcResourceInstance2.setDescription("VFC instance 2"); - vfcResourceInstance2.setName(certifiedVFC2.getName()); - vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId()); - Either createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance2); - assertTrue(createResourceVfcInstance2.isLeft()); - - Either serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser); - assertTrue(serviceFetch.isLeft()); - - List componentInstances = serviceFetch.left().value().getComponentInstances(); - String ciname1 = null; - String ciname2 = null; - - for (ComponentInstance ci : componentInstances) { - if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) { - ciname1 = ci.getName(); - } - if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) { - ciname2 = ci.getName(); - } - } - - Either result = exportUtils.exportComponent(serviceFetch.left().value()); - assertTrue(result.isLeft()); - - String mainYaml = result.left().value().getMainYaml(); - assertNotNull(mainYaml); - - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes())); - log.debug(mainYaml); - - Yaml yaml = new Yaml(); - - InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes()); - Map load = (Map) yaml.load(inputStream); - Map imports = (Map) load.get("imports"); - assertNotNull(imports); - assertEquals("Validate imports size in yml", 2, imports.size()); - - Map metadata = (Map) load.get("metadata"); - assertNotNull(metadata); - validateMetadata(metadata, serviceFetch.left().value(), false); - - Map vf1 = (Map) imports.get(certifiedVFC1.getName()); - String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY); - ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName); - - Map topology_template = (Map) load.get("topology_template"); - Map node_templates = (Map) topology_template.get("node_templates"); - Map inst1 = (Map) node_templates.get(ciname1); - Map inst2 = (Map) node_templates.get(ciname2); - - Map inst1MD = (Map) inst1.get("metadata"); - Map inst2MD = (Map) inst2.get("metadata"); - - validateMetadata(inst1MD, certifiedVFC1, true); - - Map vf2 = (Map) imports.get(certifiedVFC2.getName()); - fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY); - artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName); - - validateMetadata(inst2MD, certifiedVFC2, true);*/ - } + private static final Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class); + @javax.annotation.Resource + private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; + @Autowired + private ToscaExportHandler exportUtils; + @Autowired + private ComponentInstanceOperation componentInstanceOperation; + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + @Test + public void testExportService() { + /* Resource resource1 = ResourceTestUtils.prepareResource(0); + resource1.setResourceType(ResourceTypeEnum.VF); + Either createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null); + assertTrue(createResource1.isLeft()); + Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value()); + + Resource resource2 = ResourceTestUtils.prepareResource(1); + resource2.setResourceType(ResourceTypeEnum.VF); + Either createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null); + assertTrue(createResource2.isLeft()); + Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value()); + + Service service = ResourceTestUtils.prepareService(0); + Either createService = serviceBusinessLogic.createService(service, getAdminUser()); + assertTrue(createService.isLeft()); + + // add VFC instance to VF + ComponentInstance vfcResourceInstance1 = new ComponentInstance(); + vfcResourceInstance1.setDescription("VFC instance 1"); + vfcResourceInstance1.setName(certifiedVFC1.getName()); + vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId()); + + Either createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), + vfcResourceInstance1); + assertTrue(createResourceVfcInstance1.isLeft()); + + ComponentInstance vfcResourceInstance2 = new ComponentInstance(); + vfcResourceInstance2.setDescription("VFC instance 2"); + vfcResourceInstance2.setName(certifiedVFC2.getName()); + vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId()); + Either createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), + vfcResourceInstance2); + assertTrue(createResourceVfcInstance2.isLeft()); + + Either serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser); + assertTrue(serviceFetch.isLeft()); + + List componentInstances = serviceFetch.left().value().getComponentInstances(); + String ciname1 = null; + String ciname2 = null; + + for (ComponentInstance ci : componentInstances) { + if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) { + ciname1 = ci.getName(); + } + if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) { + ciname2 = ci.getName(); + } + } + + Either result = exportUtils.exportComponent(serviceFetch.left().value()); + assertTrue(result.isLeft()); + + String mainYaml = result.left().value().getMainYaml(); + assertNotNull(mainYaml); + + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes())); + log.debug(mainYaml); + + Yaml yaml = new Yaml(); + + InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes()); + Map load = (Map) yaml.load(inputStream); + Map imports = (Map) load.get("imports"); + assertNotNull(imports); + assertEquals("Validate imports size in yml", 2, imports.size()); + + Map metadata = (Map) load.get("metadata"); + assertNotNull(metadata); + validateMetadata(metadata, serviceFetch.left().value(), false); + + Map vf1 = (Map) imports.get(certifiedVFC1.getName()); + String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY); + ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName); + + Map topology_template = (Map) load.get("topology_template"); + Map node_templates = (Map) topology_template.get("node_templates"); + Map inst1 = (Map) node_templates.get(ciname1); + Map inst2 = (Map) node_templates.get(ciname2); + + Map inst1MD = (Map) inst1.get("metadata"); + Map inst2MD = (Map) inst2.get("metadata"); + + validateMetadata(inst1MD, certifiedVFC1, true); + + Map vf2 = (Map) imports.get(certifiedVFC2.getName()); + fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY); + artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName); + + validateMetadata(inst2MD, certifiedVFC2, true);*/ + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java index 2984d25e20..8d45e42357 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java @@ -20,12 +20,7 @@ package org.openecomp.sdc.common.transaction.mngr; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - +import fj.data.Either; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -51,385 +46,389 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCode import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum; import org.slf4j.Logger; -import fj.data.Either; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class SdncTransactionTest { - private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); - private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); - private static Logger log = Mockito.spy(Logger.class); - private static int transactionId = 0; - private static ConfigurationManager configurationManager; - - public enum TestAction { - TitanAction, Rollback, GeneralAction - } - - public enum TestResponse { - TitanResponseSuccess, GeneralSuccess - } - - @BeforeClass - public static void beforeClass() { - TransactionSdncImpl.setLog(log); - CommitManager.setLog(log); - RollbackHandler.setLog(log); - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - configurationManager = new ConfigurationManager(configurationSource); - } - - @Before - public void beforeTest() { - reset(log); - reset(esCatalogDao); - reset(titanGenericDao); - } - - @Test - public void testInvokeTitanAction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - - doBasicTitanAction(transactionId, tx, false, true); - assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); - } - - @Test - public void testInvokeESAction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - - doESAddArtifactAction(transactionId, tx, true, true); - assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); - } - - @Test - public void testfinishTransaction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doFinishTransaction(transactionId, tx, true); - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - } - - @Test - public void testFinishOnClosedTransaction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doFinishTransaction(transactionId, tx, true); - - TransactionCodeEnum finishTransaction = tx.finishTransaction(); - assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED); - // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, - // transactionId, TransactionStatusEnum.CLOSED.name(), - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - - } - - @Test - public void testCallingLastActionTwice() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doBasicTitanAction(transactionId, tx, true, true); - Either doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false); - assertTrue(doBasicTitanAction.isRight()); - assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION, - // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, - // ActionTypeEnum.ADD_ARTIFACT.name()); - } - - @Test - public void testActionOnClosedTransaction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doFinishTransaction(transactionId, tx, true); - - Either eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); - assertTrue(eitherESResult.isRight()); - assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); - - Either eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); - assertTrue(eitherTitanResult.isRight()); - assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); - - Either eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess), - createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess)); - assertTrue(eitherGeneralDBAction.isRight()); - assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); - - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION, - // transactionId, TransactionUtils.DUMMY_USER, - // ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - } - - @Test - public void testBasicHappyScenario() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - - doBasicTitanAction(transactionId, tx, false, true); - assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); - - doESAddArtifactAction(transactionId, tx, true, true); - assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); - - doFinishTransaction(transactionId, tx, true); - - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - - } - - @Test - public void testRollbackSucceededOnAction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doESAddArtifactAction(transactionId, tx, false, true); - - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); - String crushMessage = "DB Crush Simulation"; - Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); - - assertTrue(eitherTransactionResult.isRight()); - assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, - // DBTypeEnum.TITAN.name(), transactionId, crushMessage, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - } - - @Test - public void testRollbackFailedOnAction() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - - doESAddArtifactAction(transactionId, tx, false, true); - - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED); - String crushMessage = "DB Crush Simulation"; - Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); - - assertTrue(eitherTransactionResult.isRight()); - assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); - assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED); - // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, - // DBTypeEnum.TITAN.name(), transactionId, crushMessage, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, - // transactionId, TransactionUtils.DUMMY_USER, - // ActionTypeEnum.ADD_ARTIFACT.name()); - // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, - // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - } - - @Test - public void testRollbackSucceededOnCommit() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doESAddArtifactAction(transactionId, tx, false, true); - doBasicTitanAction(transactionId, tx, true, true); - - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); - // finishTransaction - TransactionCodeEnum transactionCode = tx.finishTransaction(); - assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS); - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - } - - @Test - public void testRollbackFailedOnCommit() { - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - doESAddArtifactAction(transactionId, tx, false, true); - doBasicTitanAction(transactionId, tx, true, true); - - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); - String esError = "No Connection to Es"; - Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString()); - // finishTransaction - TransactionCodeEnum transactionCode = tx.finishTransaction(); - assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED); - assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, - // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - // verify(log).error(TransactionUtils.TRANSACTION_MARKER, - // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, - // DBTypeEnum.ELASTIC_SEARCH.name(), esError, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, - // transactionId, TransactionUtils.DUMMY_USER, - // ActionTypeEnum.ADD_ARTIFACT.name()); - // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, - // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - } - - @Test - public void testInvokeGeneralAction() { - when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); - int transactionId = getNextTransactionId(); - TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); - IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess); - IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess); - String crushMessage = "No DB Connection"; - IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage); - - Either eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction); - assertTrue(eitherResult.isLeft()); - assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess); - assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); - eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction); - - assertTrue(eitherResult.isRight()); - assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); - assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); - - // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, - // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, - // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - - } - - private Either doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { - // Add Titan Action - Either eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); - if (isVerifyAction) { - // Check Titan Action - assertTrue(eitherTitanResult.isLeft()); - assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess); - verify(log).debug(TestAction.TitanAction.name()); - verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verifyNoErrorsInLog(); - verifyNoInfoInLog(); - } - return eitherTitanResult; - } - - private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) { - // Prerequisite finishTransaction - when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); - // finishTransaction - TransactionCodeEnum transactionCode = tx.finishTransaction(); - if (isVerifyAction) { - // Check finishTransaction - verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - assertTrue(transactionCode == TransactionCodeEnum.SUCCESS); - } - return transactionCode; - } - - private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { - // Prerequisite ES Action - Either eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST); - when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact); - - // Add ES Action - Either eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); - - if (isVerifyAction) { - // Check Titan Action - assertTrue(eitherEsAction.isLeft()); - assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS); - verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); - verifyNoErrorsInLog(); - verifyNoInfoInLog(); - } - } - - private ESArtifactData createDummyArtifactData() { - String strData = "qweqwqweqw34e4wrwer"; - String myNodeType = "MyNewNodeType"; - ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes()); - return arData; - } - - private void verifyNoErrorsInLog() { - verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class)); - verify(log, Mockito.times(0)).error(Mockito.anyString()); - } - - private void verifyNoInfoInLog() { - verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class)); - verify(log, Mockito.times(0)).info(Mockito.anyString()); - } - - private IDBAction createBasicAction(TestAction action, TestResponse resp) { - final TestAction finalAction = action; - final TestResponse finalResp = resp; - return new IDBAction() { - @Override - public TestResponse doAction() { - log.debug(finalAction.name()); - return finalResp; - } - }; - } - - private IDBAction createCrushingAction(TestAction action, final String crushMessage) { - final TestAction finalAction = action; - return new IDBAction() { - @Override - public TestResponse doAction() { - log.debug(finalAction.name()); - throw new RuntimeException(crushMessage); - } - }; - } - - public int getNextTransactionId() { - transactionId++; - return transactionId; - } + private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class); + private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class); + private static final Logger log = Mockito.spy(Logger.class); + private static int transactionId = 0; + private static ConfigurationManager configurationManager; + + public enum TestAction { + TitanAction, Rollback, GeneralAction + } + + public enum TestResponse { + TitanResponseSuccess, GeneralSuccess + } + + @BeforeClass + public static void beforeClass() { + TransactionSdncImpl.setLog(log); + CommitManager.setLog(log); + RollbackHandler.setLog(log); + String appConfigDir = "src/test/resources/config/catalog-be"; + ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); + configurationManager = new ConfigurationManager(configurationSource); + } + + @Before + public void beforeTest() { + reset(log); + reset(esCatalogDao); + reset(titanGenericDao); + } + + @Test + public void testInvokeTitanAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testInvokeESAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + } + + @Test + public void testfinishTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + } + + @Test + public void testFinishOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + TransactionCodeEnum finishTransaction = tx.finishTransaction(); + assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED); + // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, + // transactionId, TransactionStatusEnum.CLOSED.name(), + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testCallingLastActionTwice() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doBasicTitanAction(transactionId, tx, true, true); + Either doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false); + assertTrue(doBasicTitanAction.isRight()); + assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION, + // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testActionOnClosedTransaction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doFinishTransaction(transactionId, tx, true); + + Either eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + assertTrue(eitherESResult.isRight()); + assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + assertTrue(eitherTitanResult.isRight()); + assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + Either eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess), + createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess)); + assertTrue(eitherGeneralDBAction.isRight()); + assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + @Test + public void testBasicHappyScenario() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doBasicTitanAction(transactionId, tx, false, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doESAddArtifactAction(transactionId, tx, true, true); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + + doFinishTransaction(transactionId, tx, true); + + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + } + + @Test + public void testRollbackSucceededOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String crushMessage = "DB Crush Simulation"; + Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnAction() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + + doESAddArtifactAction(transactionId, tx, false, true); + + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED); + String crushMessage = "DB Crush Simulation"; + Either eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage)); + + assertTrue(eitherTransactionResult.isRight()); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED); + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.TITAN.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackSucceededOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testRollbackFailedOnCommit() { + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + doESAddArtifactAction(transactionId, tx, false, true); + doBasicTitanAction(transactionId, tx, true, true); + + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR); + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + String esError = "No Connection to Es"; + Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString()); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED); + assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, + // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, + // DBTypeEnum.ELASTIC_SEARCH.name(), esError, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL, + // transactionId, TransactionUtils.DUMMY_USER, + // ActionTypeEnum.ADD_ARTIFACT.name()); + // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER, + // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + } + + @Test + public void testInvokeGeneralAction() { + when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK); + int transactionId = getNextTransactionId(); + TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao); + IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess); + IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess); + String crushMessage = "No DB Connection"; + IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage); + + Either eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction); + assertTrue(eitherResult.isLeft()); + assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess); + assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN); + eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction); + + assertTrue(eitherResult.isRight()); + assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS); + assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED); + + // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, + // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, + // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + + } + + private Either doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Add Titan Action + Either eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess)); + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherTitanResult.isLeft()); + assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess); + verify(log).debug(TestAction.TitanAction.name()); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + return eitherTitanResult; + } + + private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) { + // Prerequisite finishTransaction + when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK); + // finishTransaction + TransactionCodeEnum transactionCode = tx.finishTransaction(); + if (isVerifyAction) { + // Check finishTransaction + verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + assertTrue(transactionCode == TransactionCodeEnum.SUCCESS); + } + return transactionCode; + } + + private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) { + // Prerequisite ES Action + Either eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST); + when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact); + + // Add ES Action + Either eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData()); + + if (isVerifyAction) { + // Check Titan Action + assertTrue(eitherEsAction.isLeft()); + assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS); + verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name()); + verifyNoErrorsInLog(); + verifyNoInfoInLog(); + } + } + + private ESArtifactData createDummyArtifactData() { + String strData = "qweqwqweqw34e4wrwer"; + String myNodeType = "MyNewNodeType"; + ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes()); + return arData; + } + + private void verifyNoErrorsInLog() { + verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).error(Mockito.anyString()); + } + + private void verifyNoInfoInLog() { + verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class)); + verify(log, Mockito.times(0)).info(Mockito.anyString()); + } + + private IDBAction createBasicAction(TestAction action, TestResponse resp) { + final TestAction finalAction = action; + final TestResponse finalResp = resp; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + return finalResp; + } + }; + } + + private IDBAction createCrushingAction(TestAction action, final String crushMessage) { + final TestAction finalAction = action; + return new IDBAction() { + @Override + public TestResponse doAction() { + log.debug(finalAction.name()); + throw new RuntimeException(crushMessage); + } + }; + } + + public int getNextTransactionId() { + transactionId++; + return transactionId; + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java new file mode 100644 index 0000000000..95c2ac7bdd --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.cucumber.runners; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; +import org.openecomp.sdc.be.components.BeConfDependentTest; + +@RunWith(Cucumber.class) +@CucumberOptions(features = "classpath:cucumber/tenantIsolation.feature", glue = "org.openecomp.sdc.be.components.distribution.engine") + +public class RunTenantIsolationTest extends BeConfDependentTest{ + + + +} \ No newline at end of file diff --git a/catalog-be/src/test/resources/application-context-test.xml b/catalog-be/src/test/resources/application-context-test.xml new file mode 100644 index 0000000000..9d50219354 --- /dev/null +++ b/catalog-be/src/test/resources/application-context-test.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt b/catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml index 2ec7124e1c..f948f6e3cc 100644 --- a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml +++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml @@ -6,7 +6,8 @@ identificationHeaderFields: - HTTP_CSP_WSTYPE # catalog backend hostname -beFqdn: sdccatalog.att.com +beFqdn: localhost +# sdccatalog.att.com # catalog backend http port beHttpPort: 8080 @@ -20,14 +21,14 @@ beProtocol: http # catalog backend ssl port beSslPort: 8443 -version: 1.0 +version: 1.1.0 released: 2012-11-30 toscaConformanceLevel: 5.0 minToscaConformanceLevel: 3.0 titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties -titanInMemoryGraph: true -titanLockTimeout: 600 +titanInMemoryGraph: false +titanLockTimeout: 1800 # The interval to try and reconnect to titan DB when it is down during ASDC startup: titanReconnectIntervalInSeconds: 3 @@ -40,7 +41,6 @@ esReconnectIntervalInSeconds: 3 uebHealthCheckReconnectIntervalInSeconds: 15 uebHealthCheckReadTimeout: 4 - # Protocols protocols: - http @@ -74,7 +74,7 @@ neo4j: cassandraConfig: cassandraHosts: ['localhost'] - localDataCenter: + localDataCenter: datacenter1 reconnectTimeout : 30000 authenticate: false username: koko @@ -147,6 +147,7 @@ resourceTypes: &allResourceTypes - VF - VFCMT - Abstract + - CVFC # validForResourceTypes usage # validForResourceTypes: @@ -296,9 +297,6 @@ serviceDeploymentArtifacts: YANG_XML: acceptedTypes: - xml - UCPE_LAYER_2_CONFIGURATION: - acceptedTypes: - - xml VNF_CATALOG: acceptedTypes: - xml @@ -308,6 +306,10 @@ serviceDeploymentArtifacts: MODEL_QUERY_SPEC: acceptedTypes: - xml + UCPE_LAYER_2_CONFIGURATION: + acceptedTypes: + - xml + #AAI Artifacts AAI_SERVICE_MODEL: acceptedTypes: @@ -507,6 +509,7 @@ resourceInformationalArtifacts: acceptedTypes: validForResourceTypes: - VFC + - CVFC - CP - VL - VF @@ -524,6 +527,7 @@ resourceInformationalArtifacts: validForResourceTypes: - VF - VFC + - CVFC resourceInformationalDeployedArtifacts: @@ -552,6 +556,11 @@ onboarding: downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages" healthCheckUri: "/onboarding-api/v1.0/healthcheck" +dcae: + protocol: http + host: 127.0.0.1 + port: 8080 + healthCheckUri: "/dcae/healthCheck" switchoverDetector: gBeFqdn: AIO-BE.ecomp.idns.cip.com @@ -574,7 +583,7 @@ switchoverDetector: applicationL1Cache: datatypes: - enabled: false + enabled: true firstRunDelay: 10 pollIntervalInSec: 60 @@ -586,8 +595,8 @@ applicationL2Cache: servicesSizeInCache: 200 productsSizeInCache: 100 queue: - syncIntervalInSecondes: 60 - waitOnShutDownInMinutes: 30 + syncIntervalInSecondes: 43200 + waitOnShutDownInMinutes: 10 numberOfCacheWorkers: 4 toscaValidators: @@ -611,10 +620,12 @@ vfModuleProperties: genericAssetNodeTypes: VFC: org.openecomp.resource.abstract.nodes.VFC + CVFC: org.openecomp.resource.abstract.nodes.VFC VF : org.openecomp.resource.abstract.nodes.VF PNF: org.openecomp.resource.abstract.nodes.PNF Service: org.openecomp.resource.abstract.nodes.service +workloadContext: Production environmentContext: defaultValue: General_Revenue-Bearing validValues: @@ -632,3 +643,35 @@ environmentContext: - Needed_Non-Revenue - Useful_Non-Revenue - General_Non-Revenue + +dmaapConsumerConfiguration: + hosts: olsd004.wnsnet.attws.com:3905 + consumerGroup: asdc + consumerId: invalidMamaUser #mama - in Order To Consume Remove This String And Replace It With -> mama + timeoutMs: 15000 + limit: 1 + pollingInterval: 2 + topic: com.att.sdc.23911-SDCforTestDev-v001 + latitude: 32.109333 + longitude: 34.855499 + version: 1.0 + serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events + environment: TEST + partner: BOT_R + routeOffer: MR1 + protocol: https + contenttype: application/json + dme2TraceOn: true + aftEnvironment: AFTUAT + aftDme2ConnectionTimeoutMs: 15000 + aftDme2RoundtripTimeoutMs: 240000 + aftDme2ReadTimeoutMs: 50000 + dme2preferredRouterFilePath: DME2preferredRouter.txt + timeLimitForNotificationHandleMs: 0 + credential: + username: m09875@sdc.att.com + password: hmXYcznAljMSisdy8zgcag== + +dmeConfiguration: + dme2Search: DME2SEARCH + dme2Resolve: DME2RESOLVE diff --git a/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml index ac6ff13473..b59d8cc22a 100644 --- a/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml +++ b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml @@ -40,4 +40,41 @@ createTopic: partitionCount: 1 replicationCount: 1 -startDistributionEngine: true \ No newline at end of file +startDistributionEngine: true + +opEnvRecoveryIntervalSec: 180 +allowedTimeBeforeStaleSec: 300 + +aaiConfig: + httpRequestConfig: + serverRootUrl: https://aai-uint3.test.att.com:8443 + resourceNamespaces: + operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments + + httpClientConfig: + timeouts: + readTimeoutMs: 5000 + connectTimeoutMs: 1000 + clientCertificate: + keyStore: /opt/app/jetty/base/be/etc/non-prod.jks + keyStorePassword: hmXYcznAljMSisdy8zgcag== + headers: + X-FromAppId: asdc + numOfRetries: 3 + +msoConfig: + httpRequestConfig: + serverRootUrl: https://127.0.0.1/onap/mso/infra/modelDistributions/v1 + resourceNamespaces: + distributions: /distributions + + httpClientConfig: + timeouts: + readTimeoutMs: 2000 + connectTimeoutMs: 500 + basicAuthorization: + userName: asdc + password: OTLEp5lfVhYdyw5EAtTUBQ== + numOfRetries: 3 + +currentArtifactInstallationTimeout: 120 diff --git a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml index 591a961150..69fef0f979 100644 --- a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml +++ b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml @@ -1,4 +1,4 @@ -# Errors +# Errors errors: OK: { code: 200, @@ -8,6 +8,10 @@ errors: code: 201, message: "OK" } + ACCEPTED: { + code: 202, + message: "Accepted" + } NO_CONTENT: { code: 204, message: "No Content" @@ -1832,16 +1836,230 @@ errors: messageId: "SVC4668" } - #---------SVC4669----------------------------- +#---------SVC4669----------------------------- INVALID_RESOURCE_TYPE: { code: 400, message: "Error: Invalid resource type.", messageId: "SVC4669" } - - #---------SVC4670------------------------------ +#---------SVC4670------------------------------ ARTIFACT_NAME_INVALID: { code: 400, message: "Error: Artifact name is invalid.", messageId: "SVC4670" - } \ No newline at end of file + } +#---------SVC4671------------------------------ +# %1 - VSP name +# %2 - VFC name + CFVC_LOOP_DETECTED: { + code: 400, + message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2', + messageId: "SVC4671" + } +#---------SVC4672------------------------------ +# %1 - capability uniqueId +# %2 - instance uniqueId +# %3 - container uniqueId + CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested capability %1 of instance %2 was not found on the container %3.", + messageId: "SVC4672" + } +#---------SVC4673------------------------------ +# %1 - requirement uniqueId +# %2 - instance uniqueId +# %3 - container uniqueId + REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested requirement %1 of instance %2 was not found on the container %3.", + messageId: "SVC4673" + } +#---------SVC4674----------------------------- +# %1 - relation Id +# %2 - container uniqueId + RELATION_NOT_FOUND: { + code: 404, + message: "Error: Requested relation %1 was not found on the container %2.", + messageId: "SVC4674" + } + + +#---------SVC4675------------------------------ + INVALID_SERVICE_STATE: { + code: 409, + message: "Service state is invalid for this action", + messageId: "SVC4675" + } + +#---------SVC4676------------------------------ + INVALID_RESPONSE_FROM_PROXY: { + code: 502, + message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server", + messageId: "SVC4676" + } + +#---------SVC4677------------------------------ + API_RESOURCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' was not found.", + messageId: "SVC4677" + } + +#---------SVC4678------------------------------ + BAD_REQUEST_MISSING_RESOURCE: { + code: 400, + message: "Error: The required resource name/id is missing in the request", + messageId: "SVC4678" + } +#---------SVC4679------------------------------ +# %1 invalid forwarding path name + FORWARDING_PATH_INVALID_NAME: { + code: 400, + message: "Invalid forwarding path name : '%1'.", + messageId: "SVC4679" + } +#---------SVC4680------------------------------ +# %1 Forwarding path name + FORWARDING_PATH_INVALID_UNIQUE_NAME: { + code: 400, + message: "Forwarding path name is not unique : '%1'.", + messageId: "SVC4680" + } +#---------SVC4681------------------------------ +# %1 Forwarding path missing name + FORWARDING_PATH_MISSING_NAME: { + code: 400, + message: "Forwarding path name is missing.", + messageId: "SVC4681" + } +#---------SVC4671------------------------------ +# %1 - VSP name +# %2 - VFC name + CFVC_LOOP_DETECTED: { + code: 400, + message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2', + messageId: "SVC4671" + } +#---------SVC4672------------------------------ +# %1 - capability uniqueId +# %2 - instance uniqueId +# %3 - container uniqueId + CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested capability %1 of instance %2 was not found on the container %3.", + messageId: "SVC4672" + } +#---------SVC4673------------------------------ +# %1 - requirement uniqueId +# %2 - instance uniqueId +# %3 - container uniqueId + REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested requirement %1 of instance %2 was not found on the container %3.", + messageId: "SVC4673" + } +#---------SVC4674----------------------------- +# %1 - relation Id +# %2 - container uniqueId + RELATION_NOT_FOUND: { + code: 404, + message: "Error: Requested relation %1 was not found on the container %2.", + messageId: "SVC4674" + } + + +#---------SVC4675------------------------------ + INVALID_SERVICE_STATE: { + code: 409, + message: "Service state is invalid for this action", + messageId: "SVC4675" + } + +#---------SVC4676------------------------------ + INVALID_RESPONSE_FROM_PROXY: { + code: 502, + message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server", + messageId: "SVC4676" + } + +#---------SVC4677------------------------------ + API_RESOURCE_NOT_FOUND: { + code: 404, + message: "Error: Requested '%1' was not found.", + messageId: "SVC4677" + } + +#---------SVC4678------------------------------ + BAD_REQUEST_MISSING_RESOURCE: { + code: 400, + message: "Error: The required resource name/id is missing in the request", + messageId: "SVC4678" + } +#---------SVC4679------------------------------ +# %1 invalid forwarding path name + FORWARDING_PATH_INVALID_NAME: { + code: 400, + message: "Invalid forwarding path name : '%1'.", + messageId: "SVC4679" + } +#---------SVC4680------------------------------ +# %1 Forwarding path name + FORWARDING_PATH_INVALID_UNIQUE_NAME: { + code: 400, + message: "Forwarding path name is not unique : '%1'.", + messageId: "SVC4680" + } +#---------SVC4681------------------------------ +# %1 Forwarding path missing name + FORWARDING_PATH_MISSING_NAME: { + code: 400, + message: "Forwarding path name is missing.", + messageId: "SVC4681" + } +#---------SVC4682------------------------------ +# %1 - resource uniqueId +# %2 - resource component type + RESOURCE_CANNOT_CONTAIN_POLICIES: { + code: 400, + message: "Error: The resource %1 type of %2 cannot contain policies.", + messageId: "SVC4682" + } +#---------SVC4683------------------------------ +# %1 - policy uniqueId +# %2 - component uniqueId + POLICY_NOT_FOUND_ON_CONTAINER: { + code: 404, + message: "Error: Requested policy %1 was not found on the container %2.", + messageId: "SVC4683" +} +#---------SVC4684------------------------------ +# %1 - policy name + INVALID_POLICY_NAME: { + code: 400, + message: "Error: Invalid policy name %1 received.", + messageId: "SVC4684" + } +#---------SVC4685------------------------------ +# %1 - policy name + POLICY_NAME_ALREADY_EXIST: { + code: 409, + message: "Error: The policy with the name %1 already exists.", + messageId: "SVC4685" + } +#---------SVC4686------------------------------ +# %1 - policy type +# %2 - policy type + EXCLUDED_POLICY_TYPE: { + code: 400, + message: "Error: The policy of the type %1 excluded to add to a component of the type %2.", + messageId: "SVC4686" + } + +#---------SVC4687------------------------------ +# %1 External Reference Value + EXT_REF_NOT_FOUND: { + code: 404, + message: "Error: External Reference '%1' was not found.", + messageId: "SVC4687" + } + \ No newline at end of file diff --git a/catalog-be/src/test/resources/cucumber/tenantIsolation.feature b/catalog-be/src/test/resources/cucumber/tenantIsolation.feature new file mode 100644 index 0000000000..8eaac41c49 --- /dev/null +++ b/catalog-be/src/test/resources/cucumber/tenantIsolation.feature @@ -0,0 +1,42 @@ +Feature: Tenant Isolation Feature + + Scenario Outline: Recieve Notification Create Environment + #Example {"operationalEnvironmentId": "28122015552391", "operationalEnvironmentType": "ECOMP","action": "Create" } + Given Dmaap consumer recieved notification with fields + #UP, DOWN + And AAI service status is and Tenant returned is and worload returned is + And AFT_DME service status is + And UEB service status is + And Cassandra service status is + #NOT_RELEVANT, NOT_FOUND, FOUND_IN_PROGRESS (Status In Progress), FOUND_COMPLETED (Status Complete), FOUND_FAILED (Status Failed) + And Record status is + #################################################################################### + When handle message is activated + #################################################################################### + Then handle message activates validation of eventType + And trying to write message to audit log and table + And handle message activates validation of action + And handle message activates validation of state + And trying to save in-progress record + And trying to get environment info from A&AI API + And trying to retrieve Ueb Addresses From AftDme + And trying to create Ueb keys + And trying to create Ueb Topics + And handle message finished successfully + + Examples: + | notificationFields | AAIServiceStatus | tenant | worload | AftDmeServiceStatus | UebServiceStatus | CassandraServiceStatus | recordStatus | isEventTypeValidated | isAuditUpdated | isActionValidated | isStateValidated | isSaveActivated | isAAIActivated | isAftDmeActivated | isCreateKeysActivated | isCreateTopicsActivated | isSuccessfull | + | {"operationalEnvironmentType": "NON-ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | true | false | false | false | false | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Delete" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | false | false | false | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | DOWN | NOT_RELEVANT | true | false | true | true | false | false | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_IN_PROGRESS | true | false | true | true | false | false | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | | | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Update" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | true | true | true | false | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | NOT_FOUND | true | false | true | true | true | true | true | false | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | UP | DOWN | UP | NOT_FOUND | true | false | true | true | true | true | true | true | false | false | + | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | UP | UP | UP | NOT_FOUND | true | false | true | true | true | true | true | true | true | true | + | {"operationalEnvironmentType": "ECOMP","action": "Update" } | UP | TEST | ECOMP_E2E-IST | UP | UP | UP | NOT_FOUND | true | false | true | true | true | true | true | true | true | true | diff --git a/catalog-be/src/test/resources/logback-test.xml b/catalog-be/src/test/resources/logback-test.xml index d2b9bff23f..f1c51e2567 100644 --- a/catalog-be/src/test/resources/logback-test.xml +++ b/catalog-be/src/test/resources/logback-test.xml @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/catalog-be/src/test/resources/paths/elasticsearch.yml b/catalog-be/src/test/resources/paths/elasticsearch.yml new file mode 100644 index 0000000000..e1808ad7cc --- /dev/null +++ b/catalog-be/src/test/resources/paths/elasticsearch.yml @@ -0,0 +1,392 @@ + +elasticSearch.local: true +elasticSearch.transportclient: false +cluster.name: elasticsearch_1_5_2222 + +discovery.zen.ping.multicast.enabled: false +discovery.zen.ping.unicast.enabled: true +discovery.zen.ping.unicast.hosts: 1.2.3.4 +transport.client.initial_nodes: + - 1.2.3.4:9300 + + +#plugin.types: "DeleteByQueryPlugin" + +##################### Elasticsearch Configuration Example ##################### + +# This file contains an overview of various configuration settings, +# targeted at operations staff. Application developers should +# consult the guide at . +# +# The installation procedure is covered at +# . +# +# Elasticsearch comes with reasonable defaults for most settings, +# so you can try it out without bothering with configuration. +# +# Most of the time, these defaults are just fine for running a production +# cluster. If you're fine-tuning your cluster, or wondering about the +# effect of certain configuration option, please _do ask_ on the +# mailing list or IRC channel [http://elasticsearch.org/community]. + +# Any element in the configuration can be replaced with environment variables +# by placing them in ${...} notation. For example: +# +# node.rack: ${RACK_ENV_VAR} + +# For information on supported formats and syntax for the config file, see +# + + +################################### Cluster ################################### + +# Cluster name identifies your cluster for auto-discovery. If you're running +# multiple clusters on the same network, make sure you're using unique names. +# +# cluster.name: elasticsearch + + +#################################### Node ##################################### + +# Node names are generated dynamically on startup, so you're relieved +# from configuring them manually. You can tie this node to a specific name: +# +# node.name: "Franz Kafka" + +# Every node can be configured to allow or deny being eligible as the master, +# and to allow or deny to store the data. +# +# Allow this node to be eligible as a master node (enabled by default): +# +# node.master: true +# +# Allow this node to store data (enabled by default): +# +# node.data: true + +# You can exploit these settings to design advanced cluster topologies. +# +# 1. You want this node to never become a master node, only to hold data. +# This will be the "workhorse" of your cluster. +# +# node.master: false +# node.data: true +# +# 2. You want this node to only serve as a master: to not store any data and +# to have free resources. This will be the "coordinator" of your cluster. +# +# node.master: true +# node.data: false +# +# 3. You want this node to be neither master nor data node, but +# to act as a "search load balancer" (fetching data from nodes, +# aggregating results, etc.) +# +# node.master: false +# node.data: false + +# Use the Cluster Health API [http://localhost:9200/_cluster/health], the +# Node Info API [http://localhost:9200/_nodes] or GUI tools +# such as , +# , +# and +# to inspect the cluster state. + +# A node can have generic attributes associated with it, which can later be used +# for customized shard allocation filtering, or allocation awareness. An attribute +# is a simple key value pair, similar to node.key: value, here is an example: +# +# node.rack: rack314 + +# By default, multiple nodes are allowed to start from the same installation location +# to disable it, set the following: +# node.max_local_storage_nodes: 1 + + +#################################### Index #################################### + +# You can set a number of options (such as shard/replica options, mapping +# or analyzer definitions, translog settings, ...) for indices globally, +# in this file. +# +# Note, that it makes more sense to configure index settings specifically for +# a certain index, either when creating it or by using the index templates API. +# +# See and +# +# for more information. + +# Set the number of shards (splits) of an index (5 by default): +# +# index.number_of_shards: 5 + +# Set the number of replicas (additional copies) of an index (1 by default): +# +# index.number_of_replicas: 1 + +# Note, that for development on a local machine, with small indices, it usually +# makes sense to "disable" the distributed features: +# +index.number_of_shards: 1 +index.number_of_replicas: 0 + +# These settings directly affect the performance of index and search operations +# in your cluster. Assuming you have enough machines to hold shards and +# replicas, the rule of thumb is: +# +# 1. Having more *shards* enhances the _indexing_ performance and allows to +# _distribute_ a big index across machines. +# 2. Having more *replicas* enhances the _search_ performance and improves the +# cluster _availability_. +# +# The "number_of_shards" is a one-time setting for an index. +# +# The "number_of_replicas" can be increased or decreased anytime, +# by using the Index Update Settings API. +# +# Elasticsearch takes care about load balancing, relocating, gathering the +# results from nodes, etc. Experiment with different settings to fine-tune +# your setup. + +# Use the Index Status API () to inspect +# the index status. + + +#################################### Paths #################################### +path.home: /src/test/resources +# Path to directory containing configuration (this file and logging.yml): +# +path.conf: /src/test/resources + +# Path to directory where to store index data allocated for this node. +# +path.data: target/esdata +# +# Can optionally include more than one location, causing data to be striped across +# the locations (a la RAID 0) on a file level, favouring locations with most free +# space on creation. For example: +# +# path.data: /path/to/data1,/path/to/data2 + +# Path to temporary files: +# +path.work: /target/eswork + +# Path to log files: +# +path.logs: /target/eslogs + +# Path to where plugins are installed: +# +# path.plugins: /path/to/plugins + + +#################################### Plugin ################################### + +# If a plugin listed here is not installed for current node, the node will not start. +# +# plugin.mandatory: mapper-attachments,lang-groovy + + +################################### Memory #################################### + +# Elasticsearch performs poorly when JVM starts swapping: you should ensure that +# it _never_ swaps. +# +# Set this property to true to lock the memory: +# +# bootstrap.mlockall: true + +# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set +# to the same value, and that the machine has enough memory to allocate +# for Elasticsearch, leaving enough memory for the operating system itself. +# +# You should also make sure that the Elasticsearch process is allowed to lock +# the memory, eg. by using `ulimit -l unlimited`. + + +############################## Network And HTTP ############################### + +# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens +# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node +# communication. (the range means that if the port is busy, it will automatically +# try the next port). + +# Set the bind address specifically (IPv4 or IPv6): +# +# network.bind_host: 192.168.0.1 + +# Set the address other nodes will use to communicate with this node. If not +# set, it is automatically derived. It must point to an actual IP address. +# +# network.publish_host: 192.168.0.1 + +# Set both 'bind_host' and 'publish_host': +# +# network.host: 192.168.0.1 + +# Set a custom port for the node to node communication (9300 by default): +# +# transport.tcp.port: 9300 + +# Enable compression for all communication between nodes (disabled by default): +# +# transport.tcp.compress: true + +# Set a custom port to listen for HTTP traffic: +# +# http.port: 9200 + +# Set a custom allowed content length: +# +# http.max_content_length: 100mb + +# Disable HTTP completely: +# +# http.enabled: false + + +################################### Gateway ################################### + +# The gateway allows for persisting the cluster state between full cluster +# restarts. Every change to the state (such as adding an index) will be stored +# in the gateway, and when the cluster starts up for the first time, +# it will read its state from the gateway. + +# There are several types of gateway implementations. For more information, see +# . + +# The default gateway type is the "local" gateway (recommended): +# +# gateway.type: local + +# Settings below control how and when to start the initial recovery process on +# a full cluster restart (to reuse as much local data as possible when using shared +# gateway). + +# Allow recovery process after N nodes in a cluster are up: +# +gateway.recover_after_nodes: 1 + +# Set the timeout to initiate the recovery process, once the N nodes +# from previous setting are up (accepts time value): +# +# gateway.recover_after_time: 5m + +# Set how many nodes are expected in this cluster. Once these N nodes +# are up (and recover_after_nodes is met), begin recovery process immediately +# (without waiting for recover_after_time to expire): +# +gateway.expected_nodes: 1 + + +############################# Recovery Throttling ############################# + +# These settings allow to control the process of shards allocation between +# nodes during initial recovery, replica allocation, rebalancing, +# or when adding and removing nodes. + +# Set the number of concurrent recoveries happening on a node: +# +# 1. During the initial recovery +# +# cluster.routing.allocation.node_initial_primaries_recoveries: 4 +# +# 2. During adding/removing nodes, rebalancing, etc +# +# cluster.routing.allocation.node_concurrent_recoveries: 2 + +# Set to throttle throughput when recovering (eg. 100mb, by default 20mb): +# +# indices.recovery.max_bytes_per_sec: 20mb + +# Set to limit the number of open concurrent streams when +# recovering a shard from a peer: +# +# indices.recovery.concurrent_streams: 5 + + +################################## Discovery ################################## + +# Discovery infrastructure ensures nodes can be found within a cluster +# and master node is elected. Multicast discovery is the default. + +# Set to ensure a node sees N other master eligible nodes to be considered +# operational within the cluster. Its recommended to set it to a higher value +# than 1 when running more than 2 nodes in the cluster. +# +# discovery.zen.minimum_master_nodes: 1 + +# Set the time to wait for ping responses from other nodes when discovering. +# Set this option to a higher value on a slow or congested network +# to minimize discovery failures: +# +# discovery.zen.ping.timeout: 3s + +# For more information, see +# + +# Unicast discovery allows to explicitly control which nodes will be used +# to discover the cluster. It can be used when multicast is not present, +# or to restrict the cluster communication-wise. +# +# 1. Disable multicast discovery (enabled by default): +# +# discovery.zen.ping.multicast.enabled: false +# +# 2. Configure an initial list of master nodes in the cluster +# to perform discovery when new nodes (master or data) are started: +# +# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"] + +# EC2 discovery allows to use AWS EC2 API in order to perform discovery. +# +# You have to install the cloud-aws plugin for enabling the EC2 discovery. +# +# For more information, see +# +# +# See +# for a step-by-step tutorial. + +# GCE discovery allows to use Google Compute Engine API in order to perform discovery. +# +# You have to install the cloud-gce plugin for enabling the GCE discovery. +# +# For more information, see . + +# Azure discovery allows to use Azure API in order to perform discovery. +# +# You have to install the cloud-azure plugin for enabling the Azure discovery. +# +# For more information, see . + +################################## Slow Log ################################## + +# Shard level query and fetch threshold logging. + +#index.search.slowlog.threshold.query.warn: 10s +#index.search.slowlog.threshold.query.info: 5s +#index.search.slowlog.threshold.query.debug: 2s +#index.search.slowlog.threshold.query.trace: 500ms + +#index.search.slowlog.threshold.fetch.warn: 1s +#index.search.slowlog.threshold.fetch.info: 800ms +#index.search.slowlog.threshold.fetch.debug: 500ms +#index.search.slowlog.threshold.fetch.trace: 200ms + +#index.indexing.slowlog.threshold.index.warn: 10s +#index.indexing.slowlog.threshold.index.info: 5s +#index.indexing.slowlog.threshold.index.debug: 2s +#index.indexing.slowlog.threshold.index.trace: 500ms + +################################## GC Logging ################################ + +#monitor.jvm.gc.young.warn: 1000ms +#monitor.jvm.gc.young.info: 700ms +#monitor.jvm.gc.young.debug: 400ms + +#monitor.jvm.gc.old.warn: 10s +#monitor.jvm.gc.old.info: 5s +#monitor.jvm.gc.old.debug: 2s + diff --git a/catalog-be/src/test/resources/paths/path-context.xml b/catalog-be/src/test/resources/paths/path-context.xml new file mode 100644 index 0000000000..f0067dfe55 --- /dev/null +++ b/catalog-be/src/test/resources/paths/path-context.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit 1.2.3-korg